Advertisement
_56cool_

MineOS

Dec 8th, 2016
2,635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.25 KB | None | 0 0
  1. local component = require("component")
  2. local computer = require("computer")
  3. local unicode = require("unicode")
  4. local event = require("event")
  5. local fs = require("filesystem")
  6. local serialization = require("serialization")
  7. local shell = require("shell")
  8. local args, options = shell.parse( ... )
  9.  
  10. ------------------------------------- Проверка компа на соответствие сис. требованиям -------------------------------------
  11.  
  12. shell.execute("cd ..")
  13. shell.setWorkingDirectory("")
  14.  
  15. -- Создаем массив говна
  16. local govno = {}
  17.  
  18. print(" ")
  19. print("Analyzing computer for matching system requirements...")
  20.  
  21.  
  22. --Если нашло какое-то несоответствие сис. требованиям, то написать, что именно не так
  23. if #govno > 0 and not options.skipcheck then
  24.   print(" ")
  25.   for i = 1, #govno do print(govno[i]) end
  26.   print(" ")
  27.   return
  28. else
  29.   print("Done, everything's good. Proceed to downloading.")
  30.   print(" ")
  31. end
  32.  
  33. ------------------------------------- Создание базового дерьмища -------------------------------------
  34.  
  35. local lang
  36. local applications
  37. local padColor = 0x262626
  38. local installerScale = 1
  39. local timing = 0.2
  40. local GitHubUserUrl = "https://raw.githubusercontent.com/"
  41.  
  42. local function internetRequest(url)
  43.   local success, response = pcall(component.internet.request, url)
  44.   if success then
  45.     local responseData = ""
  46.     while true do
  47.       local data, responseChunk = response.read()
  48.       if data then
  49.         responseData = responseData .. data
  50.       else
  51.         if responseChunk then
  52.           return false, responseChunk
  53.         else
  54.           return true, responseData
  55.         end
  56.       end
  57.     end
  58.   else
  59.     return false, reason
  60.   end
  61. end
  62.  
  63. --БЕЗОПАСНАЯ ЗАГРУЗОЧКА
  64. local function getFromGitHubSafely(url, path)
  65.   local success, reason = internetRequest(url)
  66.   if success then
  67.     fs.makeDirectory(fs.path(path) or "")
  68.     fs.remove(path)
  69.     local file = io.open(path, "w")
  70.     file:write(reason)
  71.     file:close()
  72.     return reason
  73.   else
  74.     error("Can't download \"" .. url .. "\"!\n")
  75.   end
  76. end
  77.  
  78. -- Прошивочка биоса на более пиздатый, нашенский
  79. local function flashEFI()
  80.   local oldBootAddress = component.eeprom.getData()
  81.   local data; local file = io.open("/MineOS/System/OS/EFI.lua", "r"); data = file:read("*a"); file:close()
  82.   component.eeprom.set(data)
  83.   component.eeprom.setLabel("EEPROM (MineOS EFI)")
  84.   component.eeprom.setData(oldBootAddress)
  85.   pcall(component.proxy(oldBootAddress).setLabel, "MineOS")
  86. end
  87.  
  88. ------------------------------------- Стадия стартовой загрузки всего необходимого -------------------------------------
  89.  
  90. print("Downloading file list")
  91. applications = serialization.unserialize(getFromGitHubSafely(GitHubUserUrl .. "IgorTimofeev/OpenComputers/master/Applications.txt", "/MineOS/System/OS/Applications.txt"))
  92. print(" ")
  93.  
  94. for i = 1, #applications do
  95.   if applications[i].preLoadFile then
  96.     print("Downloading \"" .. fs.name(applications[i].name) .. "\"")
  97.     getFromGitHubSafely(GitHubUserUrl .. applications[i].url, applications[i].name)
  98.   end
  99. end
  100.  
  101. print(" ")
  102.  
  103. ------------------------------------- Стадия инициализации загруженных библиотек -------------------------------------
  104.  
  105. package.loaded.ecs = nil
  106. package.loaded.ECSAPI = nil
  107. _G.ecs = require("ECSAPI")
  108. _G.image = require("image")
  109.  
  110. local imageOS = image.load("/MineOS/System/OS/Icons/OS_Logo.pic")
  111. local imageLanguages = image.load("/MineOS/System/OS/Icons/Languages.pic")
  112. local imageDownloading = image.load("/MineOS/System/OS/Icons/Downloading.pic")
  113. local imageOK = image.load("/MineOS/System/OS/Icons/OK.pic")
  114.  
  115. ecs.setScale(installerScale)
  116.  
  117. local xSize, ySize = component.gpu.getResolution()
  118. local windowWidth, windowHeight = 80, 25
  119. local xWindow, yWindow = math.floor(xSize / 2 - windowWidth / 2), math.ceil(ySize / 2 - windowHeight / 2)
  120. local xWindowEnd, yWindowEnd = xWindow + windowWidth - 1, yWindow + windowHeight - 1
  121.  
  122. ------------------------------------- Базовые функции для работы с будущим окном -------------------------------------
  123.  
  124. local function clear()
  125.   ecs.blankWindow(xWindow, yWindow, windowWidth, windowHeight)
  126. end
  127.  
  128. local obj = {}
  129. local function newObj(class, name, ...)
  130.   obj[class] = obj[class] or {}
  131.   obj[class][name] = {...}
  132. end
  133.  
  134. local function drawButton(name, isPressed)
  135.   local buttonColor = 0x888888
  136.   if isPressed then buttonColor = ecs.colors.blue end
  137.   local d = { ecs.drawAdaptiveButton("auto", yWindowEnd - 3, 2, 1, name, buttonColor, 0xffffff) }
  138.   newObj("buttons", name, d[1], d[2], d[3], d[4])
  139. end
  140.  
  141. local function waitForClickOnButton(buttonName)
  142.   while true do
  143.     local e = { event.pull() }
  144.     if e[1] == "touch" then
  145.       if ecs.clickedAtArea(e[3], e[4], obj["buttons"][buttonName][1], obj["buttons"][buttonName][2], obj["buttons"][buttonName][3], obj["buttons"][buttonName][4]) then
  146.         drawButton(buttonName, true)
  147.         os.sleep(timing)
  148.         break
  149.       end
  150.     end
  151.   end
  152. end
  153.  
  154. ------------------------------------- Стадия выбора языка и настройки системы -------------------------------------
  155.  
  156. ecs.prepareToExit()
  157.  
  158. local installOption, downloadWallpapers, showHelpTips
  159.  
  160. do
  161.   clear()
  162.   image.draw(math.ceil(xSize / 2 - 30), yWindow + 2, imageLanguages)
  163.  
  164.   drawButton("Select language",false)
  165.   waitForClickOnButton("Select language")
  166.  
  167.   local data = ecs.universalWindow("auto", "auto", 36, 0x262626, true,
  168.     {"EmptyLine"},
  169.     {"CenterText", ecs.colors.orange, "Select language"},
  170.     {"EmptyLine"},
  171.     {"Select", 0xFFFFFF, ecs.colors.green, "Russian", "English"},
  172.     {"EmptyLine"},
  173.     {"CenterText", ecs.colors.orange, "Change some OS properties"},
  174.     {"EmptyLine"},
  175.     {"Selector", 0xFFFFFF, 0xF2B233, "Full installation", "Install only must-have apps", "Install only libraries"},
  176.     {"EmptyLine"},
  177.     {"Switch", 0xF2B233, 0xFFFFFF, 0xFFFFFF, "Download wallpapers", true},
  178.     {"EmptyLine"},
  179.     {"Switch", 0xF2B233, 0xffffff, 0xFFFFFF, "Show help tips in OS", true},
  180.     {"EmptyLine"},
  181.     {"Button", {ecs.colors.orange, 0x262626, "OK"}}
  182.   )
  183.   installOptions, downloadWallpapers, showHelpTips = data[2], data[3], data[4]
  184.  
  185.   -- Устанавливаем базовую конфигурацию системы
  186.   _G.OSSettings = {
  187.     showHelpOnApplicationStart = showHelpTips,
  188.     language = data[1],
  189.     dockShortcuts = {
  190.       {path = "/MineOS/Applications/AppMarket.app"},
  191.       {path = "/MineOS/Applications/Finder.app"},
  192.       {path = "/MineOS/Applications/Photoshop.app"},
  193.       {path = "/MineOS/Applications/VK.app"},
  194.     }
  195.   }
  196.  
  197.   ecs.saveOSSettings()
  198.  
  199.   -- Загружаем локализацию инсталлера
  200.   ecs.info("auto", "auto", " ", " Installing language packages...")
  201.   local pathToLang = "/MineOS/System/OS/Installer/Language.lang"
  202.   getFromGitHubSafely(GitHubUserUrl .. "IgorTimofeev/OpenComputers/master/Installer/" .. _G.OSSettings.language .. ".lang", pathToLang)
  203.   getFromGitHubSafely(GitHubUserUrl .. "IgorTimofeev/OpenComputers/master/MineOS/License/" .. _G.OSSettings.language .. ".txt", "/MineOS/System/OS/License.txt")
  204.  
  205.   local file = io.open(pathToLang, "r"); lang = serialization.unserialize(file:read("*a")); file:close()
  206. end
  207.  
  208.  
  209. ------------------------------------- Проверка, желаем ли мы вообще ставить ось -------------------------------------
  210.  
  211. do
  212.   clear()
  213.  
  214.   image.draw(math.ceil(xSize / 2 - 15), yWindow + 2, imageOS)
  215.  
  216.   --Текстик по центру
  217.   component.gpu.setBackground(ecs.windowColors.background)
  218.   component.gpu.setForeground(ecs.colors.gray)
  219.   ecs.centerText("x", yWindowEnd - 5 , lang.beginOsInstall)
  220.  
  221.   --кнопа
  222.   drawButton("->",false)
  223.  
  224.   waitForClickOnButton("->")
  225.  
  226. end
  227.  
  228. ------------------------------ЛИЦ СОГЛАЩЕНЬКА------------------------------------------
  229.  
  230. do
  231.   clear()
  232.  
  233.   --Откуда рисовать условия согл
  234.   local from = 1
  235.   local xText, yText, TextWidth, TextHeight = xWindow + 4, yWindow + 2, windowWidth - 8, windowHeight - 7
  236.  
  237.   --Читаем файл с лиц соглл
  238.   local lines = {}
  239.   local file = io.open("/MineOS/System/OS/License.txt", "r")
  240.   for line in file:lines() do
  241.     table.insert(lines, line)
  242.   end
  243.   file:close()
  244.  
  245.   --Штуку рисуем
  246.   ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue)
  247.   --кнопа
  248.   drawButton(lang.acceptLicense, false)
  249.  
  250.   while true do
  251.     local e = { event.pull() }
  252.     if e[1] == "touch" then
  253.       if ecs.clickedAtArea(e[3], e[4], obj["buttons"][lang.acceptLicense][1], obj["buttons"][lang.acceptLicense][2], obj["buttons"][lang.acceptLicense][3], obj["buttons"][lang.acceptLicense][4]) then
  254.         drawButton(lang.acceptLicense, true)
  255.         os.sleep(timing)
  256.         break
  257.       end
  258.     elseif e[1] == "scroll" then
  259.       if e[5] == -1 then
  260.         if from < #lines then from = from + 2; ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue) end
  261.       else
  262.         if from > 1 then from = from - 1; ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue) end
  263.       end
  264.     end
  265.   end
  266. end
  267.  
  268. -------------------------- Подготавливаем файловую систему ----------------------------------
  269.  
  270. --Создаем стартовые пути и прочие мелочи чисто для эстетики
  271. local desktopPath = "/MineOS/Desktop/"
  272. local dockPath = "/MineOS/System/OS/Dock/"
  273. local applicationsPath = "/MineOS/Applications/"
  274. local picturesPath = "/MineOS/Pictures/"
  275.  
  276. fs.remove(desktopPath)
  277. fs.remove(dockPath)
  278.  
  279. -- fs.makeDirectory(desktopPath .. "My files")
  280. -- fs.makeDirectory(picturesPath)
  281. fs.makeDirectory(dockPath)
  282.  
  283. ------------------------------ Загрузка всего ------------------------------------------
  284.  
  285. do
  286.   local barWidth = math.floor(windowWidth * 2 / 3)
  287.   local xBar = math.floor(xSize/2-barWidth/2)
  288.   local yBar = yWindowEnd - 3
  289.  
  290.   local function drawInfo(x, y, info)
  291.     ecs.square(x, y, barWidth, 1, ecs.windowColors.background)
  292.     ecs.colorText(x, y, ecs.colors.gray, info)
  293.   end
  294.  
  295.   ecs.blankWindow(xWindow,yWindow,windowWidth,windowHeight)
  296.  
  297.   image.draw(math.floor(xSize / 2 - 33), yWindow + 2, imageDownloading)
  298.  
  299.   ecs.colorTextWithBack(xBar, yBar - 1, ecs.colors.gray, ecs.windowColors.background, lang.osInstallation)
  300.   ecs.progressBar(xBar, yBar, barWidth, 1, 0xcccccc, ecs.colors.blue, 0)
  301.   os.sleep(timing)
  302.  
  303.   -- Создаем список того, что будем загружать, в зависимости от выбранных ранее опций
  304.   local thingsToDownload = {}
  305.   for i = 1, #applications do
  306.     if
  307.       (applications[i].type == "Library" or applications[i].type == "Icon")
  308.       or
  309.       (
  310.         (installOptions ~= "Install only libraries")
  311.         and
  312.         (
  313.           (applications[i].forceDownload)
  314.           or
  315.           (applications[i].type == "Wallpaper" and downloadWallpapers)
  316.           or
  317.           (applications[i].type == "Application" and installOptions == "Full installation")
  318.         )
  319.       )
  320.     then
  321.       table.insert(thingsToDownload, applications[i])
  322.     end
  323.     --Подчищаем за собой, а то мусора нынче много
  324.     applications[i] = nil
  325.   end
  326.  
  327.   -- Загружаем все из списка
  328.   for app = 1, #thingsToDownload do
  329.     drawInfo(xBar, yBar + 1, lang.downloading .. " " .. thingsToDownload[app]["name"])
  330.     local percent = app / #thingsToDownload * 100
  331.     ecs.progressBar(xBar, yBar, barWidth, 1, 0xcccccc, ecs.colors.blue, percent)
  332.  
  333.     ecs.getOSApplication(thingsToDownload[app])
  334.   end
  335.  
  336.   os.sleep(timing)
  337.   if installOptions == "Install only libraries" then flashEFI(); ecs.prepareToExit(); computer.shutdown(true) end
  338. end
  339.  
  340. -- Создаем базовые обои рабочего стола
  341. if downloadWallpapers then
  342.   ecs.createShortCut(desktopPath .. "Pictures.lnk", picturesPath)
  343.   ecs.createShortCut("/MineOS/System/OS/Wallpaper.lnk", picturesPath .. "Sunbeams.pic")
  344. end
  345.  
  346. --Создаем файл автозагрузки--
  347. local file = io.open("autorun.lua", "w")
  348. file:write("local success, reason = pcall(loadfile(\"OS.lua\")); if not success then print(\"Ошибка: \" .. tostring(reason)) end")
  349. file:close()
  350.  
  351. -- Биосик
  352. flashEFI()
  353.  
  354. ------------------------------ Стадия перезагрузки ------------------------------------------
  355.  
  356. ecs.blankWindow(xWindow,yWindow,windowWidth,windowHeight)
  357.  
  358. image.draw(math.floor(xSize/2 - 16), math.floor(ySize/2 - 11), imageOK)
  359.  
  360. --Текстик по центру
  361. component.gpu.setBackground(ecs.windowColors.background)
  362. component.gpu.setForeground(ecs.colors.gray)
  363. ecs.centerText("x",yWindowEnd - 5, lang.needToRestart)
  364.  
  365. --Кнопа
  366. drawButton(lang.restart, false)
  367. waitForClickOnButton(lang.restart)
  368.  
  369. --Перезагружаем компик
  370. ecs.prepareToExit()
  371. computer.shutdown(true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement