initgui.js 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  1. /**
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import UIDesktop from './UI/UIDesktop.js'
  20. import UIWindow from './UI/UIWindow.js'
  21. import UIAlert from './UI/UIAlert.js'
  22. import UIWindowLogin from './UI/UIWindowLogin.js';
  23. import UIWindowSignup from './UI/UIWindowSignup.js';
  24. import path from "./lib/path.js";
  25. import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
  26. import UIWindowNewPassword from './UI/UIWindowNewPassword.js';
  27. import UIWindowLoginInProgress from './UI/UIWindowLoginInProgress.js';
  28. import UIWindowEmailConfirmationRequired from './UI/UIWindowEmailConfirmationRequired.js';
  29. import UIWindowSessionList from './UI/UIWindowSessionList.js';
  30. import UIWindowRequestPermission from './UI/UIWindowRequestPermission.js';
  31. import UIWindowChangeUsername from './UI/UIWindowChangeUsername.js';
  32. import update_last_touch_coordinates from './helpers/update_last_touch_coordinates.js';
  33. import update_title_based_on_uploads from './helpers/update_title_based_on_uploads.js';
  34. import PuterDialog from './UI/PuterDialog.js';
  35. import determine_active_container_parent from './helpers/determine_active_container_parent.js';
  36. window.initgui = async function(){
  37. let url = new URL(window.location);
  38. url = url.href;
  39. // update SDK if auth_token is different from the one in the SDK
  40. if(window.auth_token && puter.authToken !== window.auth_token)
  41. puter.setAuthToken(window.auth_token);
  42. // update SDK if api_origin is different from the one in the SDK
  43. if(window.api_origin && puter.APIOrigin !== window.api_origin)
  44. puter.setAPIOrigin(api_origin);
  45. // determine locale
  46. window.locale = window.user_preferences.language;
  47. // Checks the type of device the user is on (phone, tablet, or desktop).
  48. // Depending on the device type, it sets a class attribute on the body tag
  49. // to style or script the page differently for each device type.
  50. if(isMobile.phone)
  51. $('body').attr('class', 'device-phone');
  52. else if(isMobile.tablet)
  53. $('body').attr('class', 'device-tablet');
  54. else
  55. $('body').attr('class', 'device-desktop');
  56. // Appends a meta tag to the head of the document specifying the character encoding to be UTF-8.
  57. // This ensures that special characters and symbols display correctly across various platforms and browsers.
  58. $('head').append(`<meta charset="utf-8">`);
  59. // Appends a viewport meta tag to the head of the document, ensuring optimal display on mobile devices.
  60. // This tag sets the width of the viewport to the device width, and locks the zoom level to 1 (prevents user scaling).
  61. $('head').append(`<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">`);
  62. // GET query params provided
  63. window.url_query_params = new URLSearchParams(window.location.search);
  64. // will hold the result of the whoami API call
  65. let whoami;
  66. //--------------------------------------------------------------------------------------
  67. // Determine if an app was launched from URL
  68. // i.e. https://puter.com/app/<app_name>
  69. //--------------------------------------------------------------------------------------
  70. const url_paths = window.location.pathname.split('/').filter(element => element);
  71. if(url_paths[0]?.toLocaleLowerCase() === 'app' && url_paths[1]){
  72. window.app_launched_from_url = url_paths[1];
  73. // get query params, any param that doesn't start with 'puter.' will be passed to the app
  74. window.app_query_params = {};
  75. for (let [key, value] of url_query_params) {
  76. if(!key.startsWith('puter.'))
  77. app_query_params[key] = value;
  78. }
  79. }
  80. //--------------------------------------------------------------------------------------
  81. // Extract 'action' from URL
  82. //--------------------------------------------------------------------------------------
  83. let action;
  84. if(url_paths[0]?.toLocaleLowerCase() === 'action' && url_paths[1]){
  85. action = url_paths[1].toLowerCase();
  86. }
  87. //--------------------------------------------------------------------------------------
  88. // Determine if we are in full-page mode
  89. // i.e. https://puter.com/app/<app_name>/?puter.fullpage=true
  90. //--------------------------------------------------------------------------------------
  91. if(url_query_params.has('puter.fullpage') && (url_query_params.get('puter.fullpage') === 'false' || url_query_params.get('puter.fullpage') === '0')){
  92. window.is_fullpage_mode = false;
  93. }else if(url_query_params.has('puter.fullpage') && (url_query_params.get('puter.fullpage') === 'true' || url_query_params.get('puter.fullpage') === '1')){
  94. // In fullpage mode, we want to hide the taskbar for better UX
  95. window.taskbar_height = 0;
  96. // Puter is in fullpage mode.
  97. window.is_fullpage_mode = true;
  98. }
  99. //--------------------------------------------------------------------------------------
  100. // Is GUI embedded in a popup?
  101. // i.e. https://puter.com/?embedded_in_popup=true
  102. //--------------------------------------------------------------------------------------
  103. if(url_query_params.has('embedded_in_popup') && (url_query_params.get('embedded_in_popup') === 'true' || url_query_params.get('embedded_in_popup') === '1')){
  104. window.embedded_in_popup = true;
  105. $('body').addClass('embedded-in-popup');
  106. // determine the origin of the opener
  107. window.openerOrigin = document.referrer;
  108. // if no referrer, request it from the opener via messaging
  109. if(!document.referrer){
  110. try{
  111. openerOrigin = await requestOpenerOrigin();
  112. }catch(e){
  113. throw new Error('No referrer found');
  114. }
  115. }
  116. // this is the referrer in terms of user acquisition
  117. window.referrerStr = openerOrigin;
  118. if(action === 'sign-in' && !is_auth()){
  119. // show signup window
  120. if(await UIWindowSignup({
  121. reload_on_success: false,
  122. send_confirmation_code: false,
  123. show_close_button: false,
  124. window_options:{
  125. has_head: false,
  126. cover_page: true,
  127. }
  128. }))
  129. await getUserAppToken(openerOrigin);
  130. }
  131. else if(action === 'sign-in' && is_auth()){
  132. if(await UIWindowSessionList({
  133. reload_on_success: false,
  134. draggable_body: false,
  135. has_head: false,
  136. cover_page: true,
  137. }))
  138. await getUserAppToken(openerOrigin);
  139. }
  140. }
  141. //--------------------------------------------------------------------------------------
  142. // Get user referral code from URL query params
  143. // i.e. https://puter.com/?r=123456
  144. //--------------------------------------------------------------------------------------
  145. if(url_query_params.has('r')){
  146. window.referral_code = url_query_params.get('r');
  147. // remove 'r' from URL
  148. window.history.pushState(null, document.title, '/');
  149. // show referral notice, this will be used later if Desktop is loaded
  150. if(window.first_visit_ever)
  151. window.show_referral_notice = true;
  152. }
  153. //--------------------------------------------------------------------------------------
  154. // Action: Request Permission
  155. //--------------------------------------------------------------------------------------
  156. if(action === 'request-permission'){
  157. let app_uid = url_query_params.get('app_uid');
  158. let origin = openerOrigin ?? url_query_params.get('origin');
  159. let permission = url_query_params.get('permission');
  160. let granted = await UIWindowRequestPermission({
  161. app_uid: app_uid,
  162. origin: origin,
  163. permission: permission,
  164. });
  165. let messageTarget = embedded_in_popup ? window.opener : window.parent;
  166. messageTarget.postMessage({
  167. msg: "permissionGranted",
  168. granted: granted,
  169. }, origin);
  170. }
  171. //--------------------------------------------------------------------------------------
  172. // Action: Password recovery
  173. //--------------------------------------------------------------------------------------
  174. else if(action === 'set-new-password'){
  175. let user = url_query_params.get('user');
  176. let token = url_query_params.get('token');
  177. await UIWindowNewPassword({
  178. user: user,
  179. token: token,
  180. });
  181. }
  182. //--------------------------------------------------------------------------------------
  183. // Action: Change Username
  184. //--------------------------------------------------------------------------------------
  185. else if(action === 'change-username'){
  186. await UIWindowChangeUsername();
  187. }
  188. //--------------------------------------------------------------------------------------
  189. // Action: Login
  190. //--------------------------------------------------------------------------------------
  191. else if(action === 'login'){
  192. await UIWindowLogin();
  193. }
  194. //--------------------------------------------------------------------------------------
  195. // Action: Signup
  196. //--------------------------------------------------------------------------------------
  197. else if(action === 'signup'){
  198. await UIWindowSignup();
  199. }
  200. // -------------------------------------------------------------------------------------
  201. // If in embedded in a popup, it is important to check whether the opener app has a relationship with the user
  202. // if yes, we need to get the user app token and send it to the opener
  203. // if not, we need to ask the user for confirmation before proceeding BUT only if the action is a file-picker action
  204. // -------------------------------------------------------------------------------------
  205. if(window.embedded_in_popup && openerOrigin){
  206. let response = await checkUserSiteRelationship(openerOrigin);
  207. window.userAppToken = response.token;
  208. if(logged_in_users.length > 0 && (!userAppToken || url_query_params.get('request_auth') )){
  209. await UIWindowSessionList({
  210. reload_on_success: false,
  211. draggable_body: false,
  212. has_head: false,
  213. cover_page: true,
  214. });
  215. }
  216. // if not and action is show-open-file-picker, we need confirmation before proceeding
  217. if(action === 'show-open-file-picker' || action === 'show-save-file-picker' || action === 'show-directory-picker'){
  218. if(!userAppToken){
  219. let is_confirmed = await PuterDialog();
  220. if(is_confirmed === false){
  221. if(!is_auth()){
  222. window.first_visit_ever = false;
  223. localStorage.removeItem("has_visited_before", true);
  224. }
  225. window.close();
  226. window.open('','_self').close();
  227. }
  228. }
  229. }
  230. }
  231. // -------------------------------------------------------------------------------------
  232. // `auth_token` provided in URL, use it to log in
  233. // -------------------------------------------------------------------------------------
  234. else if(url_query_params.has('auth_token')){
  235. let query_param_auth_token = url_query_params.get('auth_token');
  236. try{
  237. whoami = await puter.os.user();
  238. }catch(e){
  239. if(e.status === 401){
  240. logout();
  241. return;
  242. }
  243. }
  244. if(whoami){
  245. if(whoami.requires_email_confirmation){
  246. let is_verified;
  247. do{
  248. is_verified = await UIWindowEmailConfirmationRequired({
  249. stay_on_top: true,
  250. has_head: false
  251. });
  252. }
  253. while(!is_verified)
  254. }
  255. // if user is logging in using an auth token that means it's not their first ever visit to Puter.com
  256. // it might be their first visit to Puter on this specific device but it's not their first time ever visiting Puter.
  257. window.first_visit_ever = false;
  258. // show login progress window
  259. UIWindowLoginInProgress({user_info: whoami});
  260. // update auth data
  261. update_auth_data(query_param_auth_token, whoami);
  262. }
  263. // remove auth_token from URL
  264. window.history.pushState(null, document.title, '/');
  265. }
  266. // -------------------------------------------------------------------------------------
  267. // Authed
  268. // -------------------------------------------------------------------------------------
  269. if(is_auth()){
  270. // try to get user data using /whoami, only if that data is missing
  271. if(!whoami){
  272. try{
  273. whoami = await puter.os.user();
  274. }catch(e){
  275. if(e.status === 401){
  276. logout();
  277. return;
  278. }
  279. }
  280. }
  281. // update local user data
  282. if(whoami){
  283. // is email confirmation required?
  284. if(whoami.requires_email_confirmation){
  285. let is_verified;
  286. do{
  287. is_verified = await UIWindowEmailConfirmationRequired({
  288. stay_on_top: true,
  289. has_head: false
  290. });
  291. }
  292. while(!is_verified)
  293. }
  294. update_auth_data(window.auth_token, whoami);
  295. // -------------------------------------------------------------------------------------
  296. // Load desktop, only if we're not embedded in a popup
  297. // -------------------------------------------------------------------------------------
  298. if(!window.embedded_in_popup){
  299. puter.fs.stat(desktop_path, async function(desktop_fsentry){
  300. UIDesktop({desktop_fsentry: desktop_fsentry});
  301. })
  302. }
  303. // -------------------------------------------------------------------------------------
  304. // If embedded in a popup, send the token to the opener and close the popup
  305. // -------------------------------------------------------------------------------------
  306. else{
  307. let msg_id = url_query_params.get('msg_id');
  308. try{
  309. let data = await getUserAppToken(new URL(openerOrigin).origin);
  310. // This is an implicit app and the app_uid is sent back from the server
  311. // we cache it here so that we can use it later
  312. window.host_app_uid = data.app_uid;
  313. // send token to parent
  314. window.opener.postMessage({
  315. msg: 'puter.token',
  316. success: true,
  317. token: data.token,
  318. app_uid: data.app_uid,
  319. username: user.username,
  320. msg_id: msg_id,
  321. }, openerOrigin);
  322. // close popup
  323. if(!action || action==='sign-in'){
  324. window.close();
  325. window.open('','_self').close();
  326. }
  327. }catch(err){
  328. // send error to parent
  329. window.opener.postMessage({
  330. msg: 'puter.token',
  331. success: false,
  332. token: null,
  333. msg_id: msg_id,
  334. }, openerOrigin);
  335. // close popup
  336. window.close();
  337. window.open('','_self').close();
  338. }
  339. let app_uid;
  340. if(openerOrigin){
  341. app_uid = await getAppUIDFromOrigin(openerOrigin);
  342. window.host_app_uid = app_uid;
  343. }
  344. if(action === 'show-open-file-picker'){
  345. let options = url_query_params.get('options');
  346. options = JSON.parse(options ?? '{}');
  347. // Open dialog
  348. UIWindow({
  349. allowed_file_types: options?.accept,
  350. selectable_body: options?.multiple,
  351. path: '/' + window.user.username + '/Desktop',
  352. // this is the uuid of the window to which this dialog will return
  353. return_to_parent_window: true,
  354. show_maximize_button: false,
  355. show_minimize_button: false,
  356. title: 'Open',
  357. is_dir: true,
  358. is_openFileDialog: true,
  359. is_resizable: false,
  360. has_head: false,
  361. cover_page: true,
  362. // selectable_body: is_selectable_body,
  363. iframe_msg_uid: msg_id,
  364. center: true,
  365. initiating_app_uuid: app_uid,
  366. on_close: function(){
  367. window.opener.postMessage({
  368. msg: "fileOpenCanceled",
  369. original_msg_id: msg_id,
  370. }, '*');
  371. }
  372. });
  373. }
  374. //--------------------------------------------------------------------------------------
  375. // Action: Show Directory Picker
  376. //--------------------------------------------------------------------------------------
  377. else if(action === 'show-directory-picker'){
  378. // open directory picker dialog
  379. UIWindow({
  380. path: '/' + window.user.username + '/Desktop',
  381. // this is the uuid of the window to which this dialog will return
  382. // parent_uuid: event.data.appInstanceID,
  383. return_to_parent_window: true,
  384. show_maximize_button: false,
  385. show_minimize_button: false,
  386. title: 'Open',
  387. is_dir: true,
  388. is_directoryPicker: true,
  389. is_resizable: false,
  390. has_head: false,
  391. cover_page: true,
  392. // selectable_body: is_selectable_body,
  393. iframe_msg_uid: msg_id,
  394. center: true,
  395. initiating_app_uuid: app_uid,
  396. on_close: function(){
  397. window.opener.postMessage({
  398. msg: "directoryOpenCanceled",
  399. original_msg_id: msg_id,
  400. }, '*');
  401. }
  402. });
  403. }
  404. //--------------------------------------------------------------------------------------
  405. // Action: Show Save File Dialog
  406. //--------------------------------------------------------------------------------------
  407. else if(action === 'show-save-file-picker'){
  408. let allowed_file_types = url_query_params.get('allowed_file_types');
  409. // send 'sendMeFileData' event to parent
  410. window.opener.postMessage({
  411. msg: 'sendMeFileData',
  412. }, '*');
  413. // listen for 'showSaveFilePickerPopup' event from parent
  414. window.addEventListener('message', async (event) => {
  415. if(event.data.msg !== 'showSaveFilePickerPopup')
  416. return;
  417. // Open dialog
  418. UIWindow({
  419. allowed_file_types: allowed_file_types,
  420. path: '/' + window.user.username + '/Desktop',
  421. // this is the uuid of the window to which this dialog will return
  422. return_to_parent_window: true,
  423. show_maximize_button: false,
  424. show_minimize_button: false,
  425. title: 'Save',
  426. is_dir: true,
  427. is_saveFileDialog: true,
  428. is_resizable: false,
  429. has_head: false,
  430. cover_page: true,
  431. // selectable_body: is_selectable_body,
  432. iframe_msg_uid: msg_id,
  433. center: true,
  434. initiating_app_uuid: app_uid,
  435. on_close: function(){
  436. window.opener.postMessage({
  437. msg: "fileSaveCanceled",
  438. original_msg_id: msg_id,
  439. }, '*');
  440. },
  441. onSaveFileDialogSave: async function(target_path, el_filedialog_window){
  442. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').show();
  443. let busy_init_ts = Date.now();
  444. let overwrite = false;
  445. let file_to_upload = new File([event.data.content], path.basename(target_path));
  446. let item_with_same_name_already_exists = true;
  447. while(item_with_same_name_already_exists){
  448. // overwrite?
  449. if(overwrite)
  450. item_with_same_name_already_exists = false;
  451. // upload
  452. try{
  453. const res = await puter.fs.write(
  454. target_path,
  455. file_to_upload,
  456. {
  457. dedupeName: false,
  458. overwrite: overwrite
  459. }
  460. );
  461. let file_signature = await puter.fs.sign(app_uid, {uid: res.uid, action: 'write'});
  462. file_signature = file_signature.items;
  463. item_with_same_name_already_exists = false;
  464. window.opener.postMessage({
  465. msg: "fileSaved",
  466. original_msg_id: msg_id,
  467. filename: res.name,
  468. saved_file: {
  469. name: file_signature.fsentry_name,
  470. readURL: file_signature.read_url,
  471. writeURL: file_signature.write_url,
  472. metadataURL: file_signature.metadata_url,
  473. type: file_signature.type,
  474. uid: file_signature.uid,
  475. path: `~/` + res.path.split('/').slice(2).join('/'),
  476. },
  477. }, '*');
  478. window.close();
  479. window.open('','_self').close();
  480. }
  481. catch(err){
  482. // item with same name exists
  483. if(err.code === 'item_with_same_name_exists'){
  484. const alert_resp = await UIAlert({
  485. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  486. buttons:[
  487. {
  488. label: i18n('replace'),
  489. value: 'replace',
  490. type: 'primary',
  491. },
  492. {
  493. label: i18n('cancel'),
  494. value: 'cancel',
  495. },
  496. ],
  497. parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
  498. })
  499. if(alert_resp === 'replace'){
  500. overwrite = true;
  501. }else if(alert_resp === 'cancel'){
  502. // enable parent window
  503. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
  504. return;
  505. }
  506. }
  507. else{
  508. console.log(err);
  509. // show error
  510. await UIAlert({
  511. message: err.message ?? "Upload failed.",
  512. parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
  513. });
  514. // enable parent window
  515. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
  516. return;
  517. }
  518. }
  519. }
  520. // done
  521. let busy_duration = (Date.now() - busy_init_ts);
  522. if( busy_duration >= busy_indicator_hide_delay){
  523. $(el_filedialog_window).close();
  524. }else{
  525. setTimeout(() => {
  526. // close this dialog
  527. $(el_filedialog_window).close();
  528. }, Math.abs(busy_indicator_hide_delay - busy_duration));
  529. }
  530. }
  531. });
  532. });
  533. }
  534. }
  535. // ----------------------------------------------------------
  536. // Get user's sites
  537. // ----------------------------------------------------------
  538. update_sites_cache();
  539. }
  540. }
  541. // -------------------------------------------------------------------------------------
  542. // Desktop Background
  543. // If we're in fullpage/emebedded/Auth Popup mode, we don't want to load the custom background
  544. // because it's not visible anyway and it's a waste of bandwidth
  545. // -------------------------------------------------------------------------------------
  546. if(!window.is_fullpage_mode && !window.embedded_in_popup){
  547. refresh_desktop_background();
  548. }
  549. // -------------------------------------------------------------------------------------
  550. // Un-authed but not first visit -> try to log in/sign up
  551. // -------------------------------------------------------------------------------------
  552. if(!is_auth() && !first_visit_ever){
  553. if(logged_in_users.length > 0){
  554. UIWindowSessionList();
  555. }
  556. else{
  557. await UIWindowLogin({
  558. reload_on_success: true,
  559. send_confirmation_code: false,
  560. window_options:{
  561. has_head: false
  562. }
  563. });
  564. }
  565. }
  566. // -------------------------------------------------------------------------------------
  567. // Un-authed and first visit ever -> create temp user
  568. // -------------------------------------------------------------------------------------
  569. else if(!is_auth() && first_visit_ever){
  570. let referrer;
  571. try{
  572. referrer = new URL(window.location.href).pathname;
  573. }catch(e){
  574. console.log(e)
  575. }
  576. referrer = window.openerOrigin ?? referrer;
  577. // a global object that will be used to store the user's referrer
  578. window.referrerStr = referrer;
  579. // in case there is also a referrer query param, add it to the referrer URL
  580. if(url_query_params.has('ref')){
  581. if(!referrer)
  582. referrer = '/';
  583. referrer += '?ref=' + html_encode(url_query_params.get('ref'));
  584. }
  585. let headers = {};
  586. if(window.custom_headers)
  587. headers = window.custom_headers;
  588. $.ajax({
  589. url: gui_origin + "/signup",
  590. type: 'POST',
  591. async: true,
  592. headers: headers,
  593. contentType: "application/json",
  594. data: JSON.stringify({
  595. referrer: referrer,
  596. referral_code: window.referral_code,
  597. is_temp: true,
  598. }),
  599. success: async function (data){
  600. update_auth_data(data.token, data.user);
  601. document.dispatchEvent(new Event("login", { bubbles: true}));
  602. },
  603. error: function (err){
  604. $('#signup-error-msg').html(err.responseText);
  605. $('#signup-error-msg').fadeIn();
  606. // re-enable 'Create Account' button
  607. $('.signup-btn').prop('disabled', false);
  608. }
  609. });
  610. }
  611. // if there is at least one window open (only non-Explorer windows), ask user for confirmation when navigating away
  612. if(feature_flags.prompt_user_when_navigation_away_from_puter){
  613. window.onbeforeunload = function(){
  614. if($(`.window:not(.window[data-app="explorer"])`).length > 0)
  615. return true;
  616. };
  617. }
  618. // -------------------------------------------------------------------------------------
  619. // `login` event handler
  620. // --------------------------------------------------------------------------------------
  621. $(document).on("login", async (e) => {
  622. // close all windows
  623. $('.window').close();
  624. // -------------------------------------------------------------------------------------
  625. // Load desktop, if not embedded in a popup
  626. // -------------------------------------------------------------------------------------
  627. if(!window.embedded_in_popup){
  628. puter.fs.stat(desktop_path, function (desktop_fsentry) {
  629. UIDesktop({ desktop_fsentry: desktop_fsentry });
  630. })
  631. }
  632. // -------------------------------------------------------------------------------------
  633. // If embedded in a popup, send the 'ready' event to referrer and close the popup
  634. // -------------------------------------------------------------------------------------
  635. else{
  636. let msg_id = url_query_params.get('msg_id');
  637. try{
  638. let data = await getUserAppToken(new URL(openerOrigin).origin);
  639. // This is an implicit app and the app_uid is sent back from the server
  640. // we cache it here so that we can use it later
  641. window.host_app_uid = data.app_uid;
  642. // send token to parent
  643. window.opener.postMessage({
  644. msg: 'puter.token',
  645. success: true,
  646. msg_id: msg_id,
  647. token: data.token,
  648. username: user.username,
  649. app_uid: data.app_uid,
  650. }, openerOrigin);
  651. // close popup
  652. if(!action || action==='sign-in'){
  653. window.close();
  654. window.open('','_self').close();
  655. }
  656. }catch(err){
  657. // send error to parent
  658. window.opener.postMessage({
  659. msg: 'puter.token',
  660. msg_id: msg_id,
  661. success: false,
  662. token: null,
  663. }, openerOrigin);
  664. // close popup
  665. window.close();
  666. window.open('','_self').close();
  667. }
  668. let app_uid;
  669. if(openerOrigin){
  670. app_uid = await getAppUIDFromOrigin(openerOrigin);
  671. window.host_app_uid = app_uid;
  672. }
  673. //--------------------------------------------------------------------------------------
  674. // Action: Show Open File Picker
  675. //--------------------------------------------------------------------------------------
  676. if(action === 'show-open-file-picker'){
  677. let options = url_query_params.get('options');
  678. options = JSON.parse(options ?? '{}');
  679. // Open dialog
  680. UIWindow({
  681. allowed_file_types: options?.accept,
  682. selectable_body: options?.multiple,
  683. path: '/' + window.user.username + '/Desktop',
  684. return_to_parent_window: true,
  685. show_maximize_button: false,
  686. show_minimize_button: false,
  687. title: 'Open',
  688. is_dir: true,
  689. is_openFileDialog: true,
  690. is_resizable: false,
  691. has_head: false,
  692. cover_page: true,
  693. iframe_msg_uid: msg_id,
  694. center: true,
  695. initiating_app_uuid: app_uid,
  696. on_close: function(){
  697. window.opener.postMessage({
  698. msg: "fileOpenCanceled",
  699. original_msg_id: msg_id,
  700. }, '*');
  701. }
  702. });
  703. }
  704. //--------------------------------------------------------------------------------------
  705. // Action: Show Directory Picker
  706. //--------------------------------------------------------------------------------------
  707. else if(action === 'show-directory-picker'){
  708. // open directory picker dialog
  709. UIWindow({
  710. path: '/' + window.user.username + '/Desktop',
  711. // this is the uuid of the window to which this dialog will return
  712. // parent_uuid: event.data.appInstanceID,
  713. return_to_parent_window: true,
  714. show_maximize_button: false,
  715. show_minimize_button: false,
  716. title: 'Open',
  717. is_dir: true,
  718. is_directoryPicker: true,
  719. is_resizable: false,
  720. has_head: false,
  721. cover_page: true,
  722. // selectable_body: is_selectable_body,
  723. iframe_msg_uid: msg_id,
  724. center: true,
  725. initiating_app_uuid: app_uid,
  726. on_close: function(){
  727. window.opener.postMessage({
  728. msg: "directoryOpenCanceled",
  729. original_msg_id: msg_id,
  730. }, '*');
  731. }
  732. });
  733. }
  734. //--------------------------------------------------------------------------------------
  735. // Action: Show Save File Dialog
  736. //--------------------------------------------------------------------------------------
  737. else if(action === 'show-save-file-picker'){
  738. let allowed_file_types = url_query_params.get('allowed_file_types');
  739. // send 'sendMeFileData' event to parent
  740. window.opener.postMessage({
  741. msg: 'sendMeFileData',
  742. }, '*');
  743. // listen for 'showSaveFilePickerPopup' event from parent
  744. window.addEventListener('message', async (event) => {
  745. if(event.data.msg !== 'showSaveFilePickerPopup')
  746. return;
  747. // Open dialog
  748. UIWindow({
  749. allowed_file_types: allowed_file_types,
  750. path: '/' + window.user.username + '/Desktop',
  751. // this is the uuid of the window to which this dialog will return
  752. return_to_parent_window: true,
  753. show_maximize_button: false,
  754. show_minimize_button: false,
  755. title: 'Save',
  756. is_dir: true,
  757. is_saveFileDialog: true,
  758. is_resizable: false,
  759. has_head: false,
  760. cover_page: true,
  761. // selectable_body: is_selectable_body,
  762. iframe_msg_uid: msg_id,
  763. center: true,
  764. initiating_app_uuid: app_uid,
  765. on_close: function(){
  766. window.opener.postMessage({
  767. msg: "fileSaveCanceled",
  768. original_msg_id: msg_id,
  769. }, '*');
  770. },
  771. onSaveFileDialogSave: async function(target_path, el_filedialog_window){
  772. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').show();
  773. let busy_init_ts = Date.now();
  774. let overwrite = false;
  775. let file_to_upload = new File([event.data.content], path.basename(target_path));
  776. let item_with_same_name_already_exists = true;
  777. while(item_with_same_name_already_exists){
  778. // overwrite?
  779. if(overwrite)
  780. item_with_same_name_already_exists = false;
  781. // upload
  782. try{
  783. const res = await puter.fs.write(
  784. target_path,
  785. file_to_upload,
  786. {
  787. dedupeName: false,
  788. overwrite: overwrite
  789. }
  790. );
  791. let file_signature = await puter.fs.sign(app_uid, {uid: res.uid, action: 'write'});
  792. file_signature = file_signature.items;
  793. item_with_same_name_already_exists = false;
  794. window.opener.postMessage({
  795. msg: "fileSaved",
  796. original_msg_id: msg_id,
  797. filename: res.name,
  798. saved_file: {
  799. name: file_signature.fsentry_name,
  800. readURL: file_signature.read_url,
  801. writeURL: file_signature.write_url,
  802. metadataURL: file_signature.metadata_url,
  803. type: file_signature.type,
  804. uid: file_signature.uid,
  805. path: `~/` + res.path.split('/').slice(2).join('/'),
  806. },
  807. }, '*');
  808. window.close();
  809. window.open('','_self').close();
  810. // show_save_account_notice_if_needed();
  811. }
  812. catch(err){
  813. // item with same name exists
  814. if(err.code === 'item_with_same_name_exists'){
  815. const alert_resp = await UIAlert({
  816. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  817. buttons:[
  818. {
  819. label: i18n('replace'),
  820. value: 'replace',
  821. type: 'primary',
  822. },
  823. {
  824. label: i18n('cancel'),
  825. value: 'cancel',
  826. },
  827. ],
  828. parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
  829. })
  830. if(alert_resp === 'replace'){
  831. overwrite = true;
  832. }else if(alert_resp === 'cancel'){
  833. // enable parent window
  834. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
  835. return;
  836. }
  837. }
  838. else{
  839. console.log(err);
  840. // show error
  841. await UIAlert({
  842. message: err.message ?? "Upload failed.",
  843. parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
  844. });
  845. // enable parent window
  846. $(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
  847. return;
  848. }
  849. }
  850. }
  851. // done
  852. let busy_duration = (Date.now() - busy_init_ts);
  853. if( busy_duration >= busy_indicator_hide_delay){
  854. $(el_filedialog_window).close();
  855. }else{
  856. setTimeout(() => {
  857. // close this dialog
  858. $(el_filedialog_window).close();
  859. }, Math.abs(busy_indicator_hide_delay - busy_duration));
  860. }
  861. }
  862. });
  863. });
  864. }
  865. }
  866. })
  867. $(".popover, .context-menu").on("remove", function () {
  868. $('.window-active .window-app-iframe').css('pointer-events', 'all');
  869. })
  870. // If the document is clicked/tapped somewhere
  871. $(document).bind("mousedown touchstart", function (e) {
  872. // update last touch coordinates
  873. update_last_touch_coordinates(e);
  874. // dismiss touchstart on regular devices
  875. if(e.type === 'touchstart' && !isMobile.phone && !isMobile.tablet)
  876. return;
  877. // If .item-container clicked, unselect all its item children
  878. if($(e.target).hasClass('item-container') && !e.ctrlKey && !e.metaKey){
  879. $(e.target).children('.item-selected').removeClass('item-selected');
  880. update_explorer_footer_selected_items_count(e.target);
  881. }
  882. // If the clicked element is not a context menu, remove all context menus
  883. if ($(e.target).parents(".context-menu").length === 0) {
  884. const $ctxmenus = $(".context-menu");
  885. $ctxmenus.fadeOut(200, function(){
  886. $ctxmenus.remove();
  887. });
  888. }
  889. // click on anything will close all popovers, but there are some exceptions
  890. if(!$(e.target).hasClass('start-app')
  891. && !$(e.target).hasClass('launch-search')
  892. && !$(e.target).hasClass('launch-search-clear')
  893. && $(e.target).closest('.start-app').length === 0
  894. && !isMobile.phone && !isMobile.table
  895. && !$(e.target).hasClass('popover')
  896. && $(e.target).parents('.popover').length === 0){
  897. $(".popover").fadeOut(200, function(){
  898. $(".popover").remove();
  899. });
  900. }
  901. // Close all tooltips
  902. $('.ui-tooltip').remove();
  903. // rename items whose names were being edited
  904. if(!$(e.target).hasClass('item-name-editor')){
  905. // blurring an Item Name Editor will automatically trigger renaming the item
  906. $(".item-name-editor-active").blur();
  907. }
  908. // update active_item_container
  909. if($(e.target).hasClass('item-container')){
  910. active_item_container = e.target;
  911. }else{
  912. let ic = $(e.target).closest('.item-container')
  913. if(ic.length > 0){
  914. active_item_container = ic.get(0);
  915. }else{
  916. let pp = $(e.target).find('.item-container')
  917. if(pp.length > 0){
  918. active_item_container = pp.get(0);
  919. }
  920. }
  921. }
  922. //active element
  923. active_element = e.target;
  924. });
  925. $(document).bind('keydown', async function(e){
  926. const focused_el = document.activeElement;
  927. //-----------------------------------------------------------------------
  928. // ← ↑ → ↓: an arrow key is pressed
  929. //-----------------------------------------------------------------------
  930. if((e.which === 37 || e.which === 38 || e.which === 39 || e.which === 40)){
  931. // ----------------------------------------------
  932. // Launch menu is open
  933. // ----------------------------------------------
  934. if($('.launch-popover').length > 0){
  935. // If no item is selected and down arrow is pressed, select the first item
  936. if($('.launch-popover .start-app-card.launch-app-selected').length === 0 && (e.which === 40)){
  937. $('.launch-popover .start-app-card:visible').first().addClass('launch-app-selected');
  938. // blur search input
  939. $('.launch-popover .launch-search').blur();
  940. return false;
  941. }
  942. // if search input is focused and left or right arrow is pressed, return false
  943. else if($('.launch-popover .launch-search').is(':focus') && (e.which === 37 || e.which === 39)){
  944. return false;
  945. }
  946. else{
  947. // If an item is already selected, move the selection up, down, left or right
  948. let selected_item = $('.launch-popover .start-app-card.launch-app-selected').get(0);
  949. let selected_item_index = $('.launch-popover .start-app-card:visible').index(selected_item);
  950. let selected_item_row = Math.floor(selected_item_index / 5);
  951. let selected_item_col = selected_item_index % 5;
  952. let selected_item_row_count = Math.ceil($('.launch-popover .start-app-card:visible').length / 5);
  953. let selected_item_col_count = 5;
  954. let new_selected_item_index = selected_item_index;
  955. let new_selected_item_row = selected_item_row;
  956. let new_selected_item_col = selected_item_col;
  957. let new_selected_item;
  958. // if up arrow is pressed
  959. if(e.which === 38){
  960. // if this item is in the first row, up arrow should bring the focus back to the search input
  961. if(selected_item_row === 0){
  962. $('.launch-popover .launch-search').focus();
  963. // unselect all items
  964. $('.launch-popover .start-app-card.launch-app-selected').removeClass('launch-app-selected');
  965. // bring cursor to the end of the search input
  966. $('.launch-popover .launch-search').val($('.launch-popover .launch-search').val());
  967. return false;
  968. }
  969. // if this item is not in the first row, move the selection up
  970. else{
  971. new_selected_item_row = selected_item_row - 1;
  972. if(new_selected_item_row < 0)
  973. new_selected_item_row = selected_item_row_count - 1;
  974. }
  975. }
  976. // if down arrow is pressed
  977. else if(e.which === 40){
  978. new_selected_item_row = selected_item_row + 1;
  979. if(new_selected_item_row >= selected_item_row_count)
  980. new_selected_item_row = 0;
  981. }
  982. // if left arrow is pressed
  983. else if(e.which === 37){
  984. new_selected_item_col = selected_item_col - 1;
  985. if(new_selected_item_col < 0)
  986. new_selected_item_col = selected_item_col_count - 1;
  987. }
  988. // if right arrow is pressed
  989. else if(e.which === 39){
  990. new_selected_item_col = selected_item_col + 1;
  991. if(new_selected_item_col >= selected_item_col_count)
  992. new_selected_item_col = 0;
  993. }
  994. new_selected_item_index = (new_selected_item_row * selected_item_col_count) + new_selected_item_col;
  995. new_selected_item = $('.launch-popover .start-app-card:visible').get(new_selected_item_index);
  996. $(selected_item).removeClass('launch-app-selected');
  997. $(new_selected_item).addClass('launch-app-selected');
  998. // make sure the selected item is visible in the popover by scrolling the popover
  999. let popover = $('.launch-popover').get(0);
  1000. let popover_height = $('.launch-popover').height();
  1001. let popover_scroll_top = popover.getBoundingClientRect().top;
  1002. let popover_scroll_bottom = popover_scroll_top + popover_height;
  1003. let selected_item_top = new_selected_item.getBoundingClientRect().top;
  1004. let selected_item_bottom = new_selected_item.getBoundingClientRect().bottom;
  1005. let isVisible = (selected_item_top >= popover_scroll_top) && (selected_item_bottom <= popover_scroll_top + popover_height);
  1006. if ( ! isVisible ) {
  1007. const scrollTop = selected_item_top - popover_scroll_top;
  1008. const scrollBot = selected_item_bottom - popover_scroll_bottom;
  1009. if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
  1010. popover.scrollTop += scrollTop;
  1011. } else {
  1012. popover.scrollTop += scrollBot;
  1013. }
  1014. }
  1015. return false;
  1016. }
  1017. }
  1018. // ----------------------------------------------
  1019. // A context menu is open
  1020. // ----------------------------------------------
  1021. else if($('.context-menu').length > 0){
  1022. // if no item is selected and down arrow is pressed, select the first item
  1023. if($('.context-menu-active .context-menu-item-active').length === 0 && (e.which === 40)){
  1024. let selected_item = $('.context-menu-active .context-menu-item').get(0);
  1025. select_ctxmenu_item(selected_item);
  1026. return false;
  1027. }
  1028. // if no item is selected and up arrow is pressed, select the last item
  1029. else if($('.context-menu-active .context-menu-item-active').length === 0 && (e.which === 38)){
  1030. let selected_item = $('.context-menu .context-menu-item').get($('.context-menu .context-menu-item').length - 1);
  1031. select_ctxmenu_item(selected_item);
  1032. return false;
  1033. }
  1034. // if an item is selected and down arrow is pressed, select the next enabled item
  1035. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 40)){
  1036. let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1037. let selected_item_index = $('.context-menu-active .context-menu-item').index(selected_item);
  1038. let new_selected_item_index = selected_item_index + 1;
  1039. let new_selected_item = $('.context-menu-active .context-menu-item').get(new_selected_item_index);
  1040. while($(new_selected_item).hasClass('context-menu-item-disabled')){
  1041. new_selected_item_index = new_selected_item_index + 1;
  1042. new_selected_item = $('.context-menu-active .context-menu-item').get(new_selected_item_index);
  1043. }
  1044. select_ctxmenu_item(new_selected_item);
  1045. return false;
  1046. }
  1047. // if an item is selected and up arrow is pressed, select the previous enabled item
  1048. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 38)){
  1049. let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1050. let selected_item_index = $('.context-menu-active .context-menu-item').index(selected_item);
  1051. let new_selected_item_index = selected_item_index - 1;
  1052. let new_selected_item = $('.context-menu-active .context-menu-item').get(new_selected_item_index);
  1053. while($(new_selected_item).hasClass('context-menu-item-disabled')){
  1054. new_selected_item_index = new_selected_item_index - 1;
  1055. new_selected_item = $('.context-menu-active .context-menu-item').get(new_selected_item_index);
  1056. }
  1057. select_ctxmenu_item(new_selected_item);
  1058. return false;
  1059. }
  1060. // if right arrow is pressed, open the submenu by triggering a mouseover event
  1061. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 39)){
  1062. const selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1063. $(selected_item).trigger('mouseover');
  1064. // if the submenu is open, select the first item in the submenu
  1065. if($(selected_item).hasClass('context-menu-item-submenu') === true){
  1066. $(selected_item).removeClass('context-menu-item-active');
  1067. $(selected_item).addClass('context-menu-item-active-blurred');
  1068. select_ctxmenu_item($('.context-menu[data-is-submenu="true"] .context-menu-item').get(0));
  1069. }
  1070. return false;
  1071. }
  1072. // if left arrow is pressed on a submenu, close the submenu
  1073. else if($('.context-menu-active[data-is-submenu="true"]').length > 0 && (e.which === 37)){
  1074. // get parent menu
  1075. let parent_menu_id = $('.context-menu-active[data-is-submenu="true"]').data('parent-id');
  1076. let parent_menu = $('.context-menu[data-element-id="' + parent_menu_id + '"]');
  1077. // remove the submenu
  1078. $('.context-menu-active[data-is-submenu="true"]').remove();
  1079. // activate the parent menu
  1080. $(parent_menu).addClass('context-menu-active');
  1081. // select the item that opened the submenu
  1082. let selected_item = $('.context-menu-active .context-menu-item-active-blurred').get(0);
  1083. $(selected_item).removeClass('context-menu-item-active-blurred');
  1084. $(selected_item).addClass('context-menu-item-active');
  1085. return false;
  1086. }
  1087. // if enter is pressed, trigger a click event on the selected item
  1088. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 13)){
  1089. let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1090. $(selected_item).trigger('click');
  1091. return false;
  1092. }
  1093. }
  1094. // ----------------------------------------------
  1095. // Navigate items in the active item container
  1096. // ----------------------------------------------
  1097. else if(!$(focused_el).is('input') && !$(focused_el).is('textarea') && (e.which === 37 || e.which === 38 || e.which === 39 || e.which === 40)){
  1098. let item_width = 110, item_height = 110, selected_item;
  1099. // select first item in container if none is selected
  1100. if($(active_item_container).find('.item-selected').length === 0){
  1101. selected_item = $(active_item_container).find('.item').get(0);
  1102. active_element = selected_item;
  1103. $(active_item_container).find('.item-selected').removeClass('item-selected');
  1104. $(selected_item).addClass('item-selected');
  1105. return false;
  1106. }
  1107. // if Shift key is pressed and ONE item is already selected, pick that item
  1108. else if($(active_item_container).find('.item-selected').length === 1 && e.shiftKey){
  1109. selected_item = $(active_item_container).find('.item-selected').get(0);
  1110. }
  1111. // if Shift key is pressed and MORE THAN ONE item is selected, pick the latest active item
  1112. else if($(active_item_container).find('.item-selected').length > 1 && e.shiftKey){
  1113. selected_item = $(active_element).hasClass('item') ? active_element : $(active_element).closest('.item').get(0);
  1114. }
  1115. // otherwise if an item is selected, pick that item
  1116. else if($(active_item_container).find('.item-selected').length === 1){
  1117. selected_item = $(active_item_container).find('.item-selected').get(0);
  1118. }
  1119. else{
  1120. selected_item = $(active_element).hasClass('item') ? active_element : $(active_element).closest('.item').get(0);
  1121. }
  1122. // override the default behavior of ctrl/meta key
  1123. // in some browsers ctrl/meta key + arrow keys will scroll the page or go back/forward in history
  1124. if(e.ctrlKey || e.metaKey){
  1125. e.preventDefault();
  1126. e.stopPropagation();
  1127. }
  1128. // get the position of the selected item
  1129. let active_el_pos = $(selected_item).hasClass('item') ? selected_item.getBoundingClientRect() : $(selected_item).closest('.item').get(0).getBoundingClientRect();
  1130. let xpos = active_el_pos.left + item_width/2;
  1131. let ypos = active_el_pos.top + item_height/2;
  1132. // these hold next item's position on the grid
  1133. let x_nxtpos, y_nxtpos;
  1134. // these hold the amount of pixels to scroll the container
  1135. let x_scroll = 0, y_scroll = 0;
  1136. // determine next item's position on the grid
  1137. // left
  1138. if(e.which === 37){
  1139. x_nxtpos = (xpos - item_width) > 0 ? (xpos - item_width) : 0;
  1140. y_nxtpos = (ypos);
  1141. x_scroll = (item_width / 2);
  1142. }
  1143. // up
  1144. else if(e.which === 38){
  1145. x_nxtpos = (xpos);
  1146. y_nxtpos = (ypos - item_height) > 0 ? (ypos - item_height) : 0;
  1147. y_scroll = -1 * (item_height / 2);
  1148. }
  1149. // right
  1150. else if(e.which === 39){
  1151. x_nxtpos = (xpos + item_width);
  1152. y_nxtpos = (ypos);
  1153. x_scroll = -1 * (item_width / 2);
  1154. }
  1155. // down
  1156. else if(e.which === 40){
  1157. x_nxtpos = (xpos);
  1158. y_nxtpos = (ypos + item_height);
  1159. y_scroll = (item_height / 2);
  1160. }
  1161. let elements_at_next_pos = document.elementsFromPoint(x_nxtpos, y_nxtpos);
  1162. let next_item;
  1163. for (let index = 0; index < elements_at_next_pos.length; index++) {
  1164. const elem_at_next_pos = elements_at_next_pos[index];
  1165. if($(elem_at_next_pos).hasClass('item') && $(elem_at_next_pos).closest('.item-container').is(active_item_container)){
  1166. next_item = elem_at_next_pos;
  1167. break;
  1168. }
  1169. }
  1170. if(next_item){
  1171. selected_item = next_item;
  1172. active_element = next_item;
  1173. // if ctrl or meta key is not pressed, unselect all items
  1174. if(!e.shiftKey){
  1175. $(active_item_container).find('.item').removeClass('item-selected');
  1176. }
  1177. $(next_item).addClass('item-selected');
  1178. window.latest_selected_item = next_item;
  1179. // scroll to the selected item only if this was a down or up move
  1180. if(e.which === 38 || e.which === 40)
  1181. next_item.scrollIntoView(false);
  1182. }
  1183. }
  1184. }
  1185. //-----------------------------------------------------------------------
  1186. // if the Esc key is pressed on a FileDialog/Alert, close that FileDialog/Alert
  1187. //-----------------------------------------------------------------------
  1188. else if(
  1189. // escape key code
  1190. e.which === 27 &&
  1191. // active window must be a FileDialog or Alert
  1192. ($('.window-active').hasClass('window-filedialog') || $('.window-active').hasClass('window-alert')) &&
  1193. // either don't close if an input is focused or if the input is the filename input
  1194. ((!$(focused_el).is('input') && !$(focused_el).is('textarea')) || $(focused_el).hasClass('savefiledialog-filename'))
  1195. ){
  1196. // close the FileDialog
  1197. $('.window-active').close();
  1198. }
  1199. //-----------------------------------------------------------------------
  1200. // if the Esc key is pressed on a Window Navbar Editor, deactivate the editor
  1201. //-----------------------------------------------------------------------
  1202. else if( e.which === 27 && $(focused_el).hasClass('window-navbar-path-input')){
  1203. $(focused_el).blur();
  1204. $(focused_el).val($(focused_el).closest('.window').attr('data-path'));
  1205. $(focused_el).attr('data-path', $(focused_el).closest('.window').attr('data-path'));
  1206. }
  1207. //-----------------------------------------------------------------------
  1208. // Esc key should:
  1209. // - always close open context menus
  1210. // - close the Launch Popover if it's open
  1211. //-----------------------------------------------------------------------
  1212. if( e.which === 27){
  1213. // close open context menus
  1214. $('.context-menu').remove();
  1215. // close the Launch Popover if it's open
  1216. $(".launch-popover").closest('.popover').fadeOut(200, function(){
  1217. $(".launch-popover").closest('.popover').remove();
  1218. });
  1219. }
  1220. })
  1221. $(document).bind('keydown', async function(e){
  1222. const focused_el = document.activeElement;
  1223. //-----------------------------------------------------------------------
  1224. // Shift+Delete (win)/ option+command+delete (Mac) key pressed
  1225. // Permanent delete bypassing trash after alert
  1226. //-----------------------------------------------------------------------
  1227. if((e.keyCode === 46 && e.shiftKey) || (e.altKey && e.metaKey && e.keyCode === 8)) {
  1228. let $selected_items = $(active_element).closest(`.item-container`).find(`.item-selected`);
  1229. if($selected_items.length > 0){
  1230. const alert_resp = await UIAlert({
  1231. message: i18n('confirm_delete_multiple_items'),
  1232. buttons:[
  1233. {
  1234. label: i18n('delete'),
  1235. type: 'primary',
  1236. },
  1237. {
  1238. label: i18n('cancel')
  1239. },
  1240. ]
  1241. })
  1242. if((alert_resp) === 'Delete'){
  1243. for (let index = 0; index < $selected_items.length; index++) {
  1244. const element = $selected_items[index];
  1245. await delete_item(element);
  1246. }
  1247. }
  1248. }
  1249. return false;
  1250. }
  1251. //-----------------------------------------------------------------------
  1252. // Delete (win)/ ctrl+delete (Mac) / cmd+delete (Mac) key pressed
  1253. // Permanent delete from trash after alert or move to trash
  1254. //-----------------------------------------------------------------------
  1255. if(e.keyCode === 46 || (e.keyCode === 8 && (e.ctrlKey || e.metaKey))) {
  1256. // permanent delete?
  1257. let $selected_items = $(active_element).closest(`.item-container`).find(`.item-selected[data-path^="${trash_path + '/'}"]`);
  1258. if($selected_items.length > 0){
  1259. const alert_resp = await UIAlert({
  1260. message: i18n('confirm_delete_multiple_items'),
  1261. buttons:[
  1262. {
  1263. label: i18n('delete'),
  1264. type: 'primary',
  1265. },
  1266. {
  1267. label: i18n('cancel')
  1268. },
  1269. ]
  1270. })
  1271. if((alert_resp) === 'Delete'){
  1272. for (let index = 0; index < $selected_items.length; index++) {
  1273. const element = $selected_items[index];
  1274. await delete_item(element);
  1275. }
  1276. const trash = await puter.fs.stat(trash_path);
  1277. if(window.socket){
  1278. window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
  1279. }
  1280. if(trash.is_empty){
  1281. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  1282. $(`.item[data-path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  1283. $(`.window[data-path="${html_encode(trash_path)}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  1284. }
  1285. }
  1286. }
  1287. // regular delete?
  1288. else{
  1289. $selected_items = $(active_element).closest('.item-container').find('.item-selected');
  1290. if($selected_items.length > 0){
  1291. // Only delete the items if we're not renaming one.
  1292. if ($selected_items.children('.item-name-editor-active').length === 0) {
  1293. move_items($selected_items, trash_path);
  1294. }
  1295. }
  1296. }
  1297. return false;
  1298. }
  1299. //-----------------------------------------------------------------------
  1300. // A letter or number is pressed and there is no context menu open: search items by name
  1301. //-----------------------------------------------------------------------
  1302. if(!e.ctrlKey && !e.metaKey && !$(focused_el).is('input') && !$(focused_el).is('textarea') && $('.context-menu').length === 0){
  1303. if(keypress_item_seach_term !== '')
  1304. clearTimeout(keypress_item_seach_buffer_timeout);
  1305. keypress_item_seach_buffer_timeout = setTimeout(()=>{
  1306. keypress_item_seach_term = '';
  1307. }, 700);
  1308. keypress_item_seach_term += e.key.toLocaleLowerCase();
  1309. let matches= [];
  1310. const selected_items = $(active_item_container).find(`.item-selected`).not('.item-disabled').first();
  1311. // if one item is selected and the selected item matches the search term, don't continue search and select this item again
  1312. if(selected_items.length === 1 && $(selected_items).attr('data-name').toLowerCase().startsWith(keypress_item_seach_term)){
  1313. return false;
  1314. }
  1315. // search for matches
  1316. let haystack = $(active_item_container).find(`.item`).not('.item-disabled');
  1317. for(let j=0; j < haystack.length; j++){
  1318. if($(haystack[j]).attr('data-name').toLowerCase().startsWith(keypress_item_seach_term)){
  1319. matches.push(haystack[j])
  1320. }
  1321. }
  1322. if(matches.length > 0){
  1323. // if there are multiple matches and an item is already selected, remove all matches before the selected item
  1324. if(selected_items.length > 0 && matches.length > 1){
  1325. let match_index;
  1326. for(let i=0; i < matches.length - 1; i++){
  1327. if($(matches[i]).is(selected_items)){
  1328. match_index = i;
  1329. break;
  1330. }
  1331. }
  1332. matches.splice(0, match_index+1);
  1333. }
  1334. // deselect all selected sibling items
  1335. $(active_item_container).find(`.item-selected`).removeClass('item-selected');
  1336. // select matching item
  1337. $(matches[0]).not('.item-disabled').addClass('item-selected');
  1338. matches[0].scrollIntoView(false);
  1339. update_explorer_footer_selected_items_count($(active_element).closest('.window'));
  1340. }
  1341. return false;
  1342. }
  1343. //-----------------------------------------------------------------------
  1344. // A letter or number is pressed and there is a context menu open: search items by name
  1345. //-----------------------------------------------------------------------
  1346. else if(!e.ctrlKey && !e.metaKey && !$(focused_el).is('input') && !$(focused_el).is('textarea') && $('.context-menu').length > 0){
  1347. if(keypress_item_seach_term !== '')
  1348. clearTimeout(keypress_item_seach_buffer_timeout);
  1349. keypress_item_seach_buffer_timeout = setTimeout(()=>{
  1350. keypress_item_seach_term = '';
  1351. }, 700);
  1352. keypress_item_seach_term += e.key.toLocaleLowerCase();
  1353. let matches= [];
  1354. const selected_items = $('.context-menu').find(`.context-menu-item-active`).first();
  1355. // if one item is selected and the selected item matches the search term, don't continue search and select this item again
  1356. if(selected_items.length === 1 && $(selected_items).text().toLowerCase().startsWith(keypress_item_seach_term)){
  1357. return false;
  1358. }
  1359. // search for matches
  1360. let haystack = $('.context-menu-active').find(`.context-menu-item`);
  1361. for(let j=0; j < haystack.length; j++){
  1362. if($(haystack[j]).text().toLowerCase().startsWith(keypress_item_seach_term)){
  1363. matches.push(haystack[j])
  1364. }
  1365. }
  1366. if(matches.length > 0){
  1367. // if there are multiple matches and an item is already selected, remove all matches before the selected item
  1368. if(selected_items.length > 0 && matches.length > 1){
  1369. let match_index;
  1370. for(let i=0; i < matches.length - 1; i++){
  1371. if($(matches[i]).is(selected_items)){
  1372. match_index = i;
  1373. break;
  1374. }
  1375. }
  1376. matches.splice(0, match_index+1);
  1377. }
  1378. // deselect all selected sibling items
  1379. $('.context-menu').find(`.context-menu-item-active`).removeClass('context-menu-item-active');
  1380. // select matching item
  1381. $(matches[0]).addClass('context-menu-item-active');
  1382. // matches[0].scrollIntoView(false);
  1383. // update_explorer_footer_selected_items_count($(active_element).closest('.window'));
  1384. }
  1385. return false;
  1386. }
  1387. })
  1388. $(document).bind("keyup keydown", async function(e){
  1389. const focused_el = document.activeElement;
  1390. //-----------------------------------------------------------------------------
  1391. // Override ctrl/cmd + s/o
  1392. //-----------------------------------------------------------------------------
  1393. if((e.ctrlKey || e.metaKey) && (e.which === 83 || e.which === 79)){
  1394. e.preventDefault()
  1395. return false;
  1396. }
  1397. //-----------------------------------------------------------------------------
  1398. // Select All
  1399. // ctrl/command + a, will select all items on desktop and windows
  1400. //-----------------------------------------------------------------------------
  1401. if((e.ctrlKey || e.metaKey) && e.which === 65 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1402. let $parent_container = $(active_element).closest('.item-container');
  1403. if($parent_container.length === 0)
  1404. $parent_container = $(active_element).find('.item-container');
  1405. if($parent_container.attr('data-multiselectable') === 'false')
  1406. return false;
  1407. if($parent_container){
  1408. $($parent_container).find('.item').not('.item-disabled').addClass('item-selected');
  1409. update_explorer_footer_selected_items_count($parent_container.closest('.window'));
  1410. }
  1411. return false;
  1412. }
  1413. //-----------------------------------------------------------------------------
  1414. // Close Window
  1415. // ctrl + w, will close the active window
  1416. //-----------------------------------------------------------------------------
  1417. if(e.ctrlKey && e.which === 87){
  1418. let $parent_window = $(active_element).closest('.window');
  1419. if($parent_window.length === 0)
  1420. $parent_window = $(active_element).find('.window');
  1421. if($parent_window !== null){
  1422. $($parent_window).close();
  1423. }
  1424. }
  1425. //-----------------------------------------------------------------------------
  1426. // Copy
  1427. // ctrl/command + c, will copy selected items on the active element to the clipboard
  1428. //-----------------------------------------------------------------------------
  1429. if((e.ctrlKey || e.metaKey) && e.which === 67 &&
  1430. $(mouseover_window).attr('data-is_dir') !== 'false' &&
  1431. $(mouseover_window).attr('data-path') !== trash_path &&
  1432. !$(focused_el).is('input') &&
  1433. !$(focused_el).is('textarea')){
  1434. let $selected_items;
  1435. let parent_container = $(active_element).closest('.item-container');
  1436. if(parent_container.length === 0)
  1437. parent_container = $(active_element).find('.item-container');
  1438. if(parent_container !== null){
  1439. $selected_items = $(parent_container).find('.item-selected');
  1440. if($selected_items.length > 0){
  1441. clipboard = [];
  1442. clipboard_op = 'copy';
  1443. $selected_items.each(function() {
  1444. // error if trash is being copied
  1445. if($(this).attr('data-path') === trash_path){
  1446. return;
  1447. }
  1448. // add to clipboard
  1449. clipboard.push({path: $(this).attr('data-path'), uid: $(this).attr('data-uid'), metadata: $(this).attr('data-metadata')});
  1450. })
  1451. }
  1452. }
  1453. return false;
  1454. }
  1455. //-----------------------------------------------------------------------------
  1456. // Cut
  1457. // ctrl/command + x, will copy selected items on the active element to the clipboard
  1458. //-----------------------------------------------------------------------------
  1459. if((e.ctrlKey || e.metaKey) && e.which === 88 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1460. let $selected_items;
  1461. let parent_container = $(active_element).closest('.item-container');
  1462. if(parent_container.length === 0)
  1463. parent_container = $(active_element).find('.item-container');
  1464. if(parent_container !== null){
  1465. $selected_items = $(parent_container).find('.item-selected');
  1466. if($selected_items.length > 0){
  1467. clipboard = [];
  1468. clipboard_op = 'move';
  1469. $selected_items.each(function() {
  1470. clipboard.push($(this).attr('data-path'));
  1471. })
  1472. }
  1473. }
  1474. return false;
  1475. }
  1476. //-----------------------------------------------------------------------
  1477. // Open
  1478. // Enter key on a selected item will open it
  1479. //-----------------------------------------------------------------------
  1480. if(e.which === 13 && !$(focused_el).is('input') && !$(focused_el).is('textarea') && (Date.now() - last_enter_pressed_to_rename_ts) >200
  1481. // prevent firing twice, because this will be fired on both keyup and keydown
  1482. && e.type === 'keydown'){
  1483. let $selected_items;
  1484. e.preventDefault();
  1485. e.stopPropagation();
  1486. // ---------------------------------------------
  1487. // if this is a selected Launch menu item, open it
  1488. // ---------------------------------------------
  1489. if($('.launch-app-selected').length > 0){
  1490. // close launch menu
  1491. $(".launch-popover").fadeOut(200, function(){
  1492. launch_app({
  1493. name: $('.launch-app-selected').attr('data-name'),
  1494. })
  1495. $(".launch-popover").remove();
  1496. });
  1497. return false;
  1498. }
  1499. // ---------------------------------------------
  1500. // if this is a selected context menu item, open it
  1501. // ---------------------------------------------
  1502. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 13)){
  1503. // let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1504. // $(selected_item).trigger('mouseover');
  1505. // $(selected_item).trigger('click');
  1506. let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1507. $(selected_item).removeClass('context-menu-item-active');
  1508. $(selected_item).addClass('context-menu-item-active-blurred');
  1509. $(selected_item).trigger('mouseover');
  1510. $(selected_item).trigger('click');
  1511. if($('.context-menu[data-is-submenu="true"]').length > 0){
  1512. let selected_item = $('.context-menu[data-is-submenu="true"] .context-menu-item').get(0);
  1513. select_ctxmenu_item(selected_item);
  1514. }
  1515. return false;
  1516. }
  1517. // ---------------------------------------------
  1518. // if this is a selected item, open it
  1519. // ---------------------------------------------
  1520. else if(active_item_container){
  1521. $selected_items = $(active_item_container).find('.item-selected');
  1522. if($selected_items.length > 0){
  1523. $selected_items.each(function() {
  1524. open_item({
  1525. item: this,
  1526. new_window: e.metaKey || e.ctrlKey,
  1527. });
  1528. })
  1529. }
  1530. return false;
  1531. }
  1532. return false;
  1533. }
  1534. //----------------------------------------------
  1535. // Paste
  1536. // ctrl/command + v, will paste items from the clipboard to the active element
  1537. //----------------------------------------------
  1538. if((e.ctrlKey || e.metaKey) && e.which === 86 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1539. let target_path, target_el;
  1540. // continue only if there is something in the clipboard
  1541. if(clipboard.length === 0)
  1542. return;
  1543. let parent_container = determine_active_container_parent();
  1544. if(parent_container){
  1545. target_el = parent_container;
  1546. target_path = $(parent_container).attr('data-path');
  1547. // don't allow pasting in Trash
  1548. if((target_path === trash_path || target_path.startsWith(trash_path + '/')) && clipboard_op !== 'move')
  1549. return;
  1550. // execute clipboard operation
  1551. if(clipboard_op === 'copy')
  1552. copy_clipboard_items(target_path);
  1553. else if(clipboard_op === 'move')
  1554. move_clipboard_items(target_el, target_path);
  1555. }
  1556. return false;
  1557. }
  1558. //-----------------------------------------------------------------------------
  1559. // Undo
  1560. // ctrl/command + z, will undo last action
  1561. //-----------------------------------------------------------------------------
  1562. if((e.ctrlKey || e.metaKey) && e.which === 90){
  1563. undo_last_action();
  1564. return false;
  1565. }
  1566. });
  1567. $(document).on('click', '.remove-permission-link', async function(e){
  1568. const el_remove_perm_link= this;
  1569. const perm_uid = $(el_remove_perm_link).attr('data-perm-uid');
  1570. $.ajax({
  1571. url: api_origin + "/remove-perm",
  1572. type: 'POST',
  1573. async: true,
  1574. contentType: "application/json",
  1575. data: JSON.stringify({
  1576. uid: perm_uid,
  1577. }),
  1578. headers: {
  1579. "Authorization": "Bearer "+auth_token
  1580. },
  1581. statusCode: {
  1582. 401: function () {
  1583. logout();
  1584. },
  1585. },
  1586. success: async function (res){
  1587. $(`[data-perm-uid="${perm_uid}"]`).hide("slide", { direction: "right" }, 300, function(e){
  1588. $(this).remove();
  1589. });
  1590. },
  1591. complete: function(){
  1592. }
  1593. })
  1594. })
  1595. // update mouse position coordinates
  1596. $(document).mousemove(function(event){
  1597. mouseX = event.clientX;
  1598. mouseY = event.clientY;
  1599. // mouse in top-left corner of screen
  1600. if((mouseX < 150 && mouseY < toolbar_height + 20) || (mouseX < 20 && mouseY < 150))
  1601. current_active_snap_zone = 'nw';
  1602. // mouse in left edge of screen
  1603. else if(mouseX < 20 && mouseY >= 150 && mouseY < desktop_height - 150)
  1604. current_active_snap_zone = 'w';
  1605. // mouse in bottom-left corner of screen
  1606. else if(mouseX < 20 && mouseY > desktop_height - 150)
  1607. current_active_snap_zone = 'sw';
  1608. // mouse in right edge of screen
  1609. else if(mouseX > desktop_width - 20 && mouseY >= 150 && mouseY < desktop_height - 150)
  1610. current_active_snap_zone = 'e';
  1611. // mouse in top-right corner of screen
  1612. else if((mouseX > desktop_width - 150 && mouseY < toolbar_height + 20) || (mouseX > desktop_width - 20 && mouseY < 150))
  1613. current_active_snap_zone = 'ne';
  1614. // mouse in bottom-right corner of screen
  1615. else if(mouseX > desktop_width - 20 && mouseY >= desktop_height - 150)
  1616. current_active_snap_zone = 'se';
  1617. // mouse in top edge of screen
  1618. else if(mouseY < toolbar_height + 20 && mouseX >= 150 && mouseX < desktop_width - 150)
  1619. current_active_snap_zone = 'n';
  1620. // not in any snap zone
  1621. else
  1622. current_active_snap_zone = undefined;
  1623. // mouseover_window
  1624. var windows = document.getElementsByClassName("window");
  1625. let active_win;
  1626. if(windows.length > 0){
  1627. let highest_window_zindex = 0;
  1628. for(let i=0; i<windows.length; i++){
  1629. const rect = windows[i].getBoundingClientRect();
  1630. if( mouseX > rect.x && mouseX < (rect.x + rect.width) && mouseY > rect.y && mouseY < (rect.y + rect.height)){
  1631. if(parseInt($(windows[i]).css('z-index')) >= highest_window_zindex){
  1632. active_win = windows[i];
  1633. highest_window_zindex = parseInt($(windows[i]).css('z-index'));
  1634. }
  1635. }
  1636. }
  1637. }
  1638. window.mouseover_window = active_win;
  1639. // mouseover_item_container
  1640. var item_containers = document.getElementsByClassName("item-container");
  1641. let active_ic;
  1642. if(item_containers.length > 0){
  1643. let highest_window_zindex = 0;
  1644. for(let i=0; i<item_containers.length; i++){
  1645. const rect = item_containers[i].getBoundingClientRect();
  1646. if( mouseX > rect.x && mouseX < (rect.x + rect.width) && mouseY > rect.y && mouseY < (rect.y + rect.height)){
  1647. let active_container_zindex = parseInt($(item_containers[i]).closest('.window').css('z-index'));
  1648. if( !isNaN(active_container_zindex) && active_container_zindex >= highest_window_zindex){
  1649. active_ic = item_containers[i];
  1650. highest_window_zindex = active_container_zindex;
  1651. }
  1652. }
  1653. }
  1654. }
  1655. window.mouseover_item_container = active_ic;
  1656. });
  1657. //--------------------------------------------------------
  1658. // Window Activation
  1659. //--------------------------------------------------------
  1660. $(document).on('mousedown', function(e){
  1661. // if taskbar or any parts of it is clicked, drop the event
  1662. if($(e.target).hasClass('taskbar') || $(e.target).closest('.taskbar').length > 0)
  1663. return;
  1664. // if mouse is clicked on a window, activate it
  1665. if(mouseover_window !== undefined){
  1666. $(mouseover_window).focusWindow(e);
  1667. }
  1668. })
  1669. // if an element has the .long-hover class, fire a long-hover event after 600ms
  1670. $(document).on('mouseenter', '.long-hover', function(){
  1671. let el = this;
  1672. el.long_hover_timeout = setTimeout(() => {
  1673. $(el).trigger('long-hover');
  1674. }, 600);
  1675. })
  1676. // if an element has the .long-hover class, cancel the long-hover event if the mouse leaves
  1677. $(document).on('mouseleave', '.long-hover', function(){
  1678. clearTimeout(this.long_hover_timeout);
  1679. })
  1680. // if an element has the .long-hover class, cancel the long-hover event if the mouse leaves
  1681. $(document).on('paste', function(event){
  1682. event = event.originalEvent ?? event;
  1683. let clipboardData = event.clipboardData || window.clipboardData;
  1684. let items = clipboardData.items || clipboardData.files;
  1685. // return if paste is on input or textarea
  1686. if($(event.target).is('input') || $(event.target).is('textarea'))
  1687. return;
  1688. if(!(items instanceof DataTransferItemList))
  1689. return;
  1690. // upload files
  1691. if(items?.length>0){
  1692. let parent_container = determine_active_container_parent();
  1693. if(parent_container){
  1694. upload_items(items, $(parent_container).attr('data-path'));
  1695. }
  1696. }
  1697. event.stopPropagation();
  1698. event.preventDefault();
  1699. return false;
  1700. })
  1701. document.addEventListener("visibilitychange", (event) => {
  1702. if (document.visibilityState !== "visible") {
  1703. window.doc_title_before_blur = document.title;
  1704. if(!_.isEmpty(window.active_uploads)){
  1705. update_title_based_on_uploads();
  1706. }
  1707. }else if(window.active_uploads){
  1708. document.title = window.doc_title_before_blur ?? 'Puter';
  1709. }
  1710. });
  1711. /**
  1712. * Event handler for a custom 'logout' event attached to the document.
  1713. * This function handles the process of logging out, including user confirmation,
  1714. * communication with the backend, and subsequent UI updates. It takes special
  1715. * precautions if the user is identified as using a temporary account.
  1716. *
  1717. * @listens Document#event:logout
  1718. * @async
  1719. * @param {Event} event - The JQuery event object associated with the logout event.
  1720. * @returns {Promise<void>} - This function does not return anything meaningful, but it performs an asynchronous operation.
  1721. */
  1722. $(document).on("logout", async function(event) {
  1723. // is temp user?
  1724. if(window.user && window.user.is_temp){
  1725. const alert_resp = await UIAlert({
  1726. message: `<strong>Save account before logging out!</strong><p>You are using a temporary account and logging out will erase all your data.</p>`,
  1727. buttons:[
  1728. {
  1729. label: i18n('save_account'),
  1730. value: 'save_account',
  1731. type: 'primary',
  1732. },
  1733. {
  1734. label: i18n('log_out'),
  1735. value: 'log_out',
  1736. type: 'danger',
  1737. },
  1738. {
  1739. label: i18n('cancel'),
  1740. },
  1741. ]
  1742. })
  1743. if(alert_resp === 'save_account'){
  1744. let saved = await UIWindowSaveAccount({
  1745. send_confirmation_code: false,
  1746. default_username: window.user.username
  1747. });
  1748. if(saved)
  1749. logout();
  1750. }else if (alert_resp === 'log_out'){
  1751. logout();
  1752. }
  1753. else{
  1754. return;
  1755. }
  1756. }
  1757. // logout
  1758. try{
  1759. await $.ajax({
  1760. url: gui_origin + "/logout",
  1761. type: 'POST',
  1762. async: true,
  1763. contentType: "application/json",
  1764. headers: {
  1765. "Authorization": "Bearer " + auth_token
  1766. },
  1767. statusCode: {
  1768. 401: function () {
  1769. },
  1770. },
  1771. })
  1772. }catch(e){
  1773. }
  1774. // remove this user from the array of logged_in_users
  1775. for (let i = 0; i < window.logged_in_users.length; i++) {
  1776. if(window.logged_in_users[i].uuid === window.user.uuid){
  1777. window.logged_in_users.splice(i, 1);
  1778. break;
  1779. }
  1780. }
  1781. // update logged_in_users in local storage
  1782. localStorage.setItem('logged_in_users', JSON.stringify(window.logged_in_users));
  1783. // delete this user from local storage
  1784. window.user = null;
  1785. localStorage.removeItem('user');
  1786. window.auth_token = null;
  1787. localStorage.removeItem('auth_token');
  1788. // close all windows
  1789. $('.window').close();
  1790. // close all ctxmenus
  1791. $('.context-menu').remove();
  1792. // remove desktop
  1793. $('.desktop').remove();
  1794. // remove taskbar
  1795. $('.taskbar').remove();
  1796. // disable native browser exit confirmation
  1797. window.onbeforeunload = null;
  1798. // go to home page
  1799. window.location.replace("/");
  1800. });
  1801. }
  1802. function requestOpenerOrigin() {
  1803. return new Promise((resolve, reject) => {
  1804. if (!window.opener) {
  1805. reject(new Error("No window.opener available"));
  1806. return;
  1807. }
  1808. // Function to handle the message event
  1809. const handleMessage = (event) => {
  1810. // Check if the message is the expected response
  1811. if (event.data.msg === 'originResponse') {
  1812. // Clean up by removing the event listener
  1813. window.removeEventListener('message', handleMessage);
  1814. resolve(event.origin);
  1815. }
  1816. };
  1817. // Set up the listener for the response
  1818. window.addEventListener('message', handleMessage, false);
  1819. // Send the request to the opener
  1820. window.opener.postMessage({ msg: 'requestOrigin' }, '*');
  1821. // Optional: Reject the promise if no response is received within a timeout
  1822. setTimeout(() => {
  1823. window.removeEventListener('message', handleMessage);
  1824. reject(new Error("Response timed out"));
  1825. }, 5000); // Timeout after 5 seconds
  1826. });
  1827. }
  1828. $(document).on('click', '.generic-close-window-button', function(e){
  1829. $(this).closest('.window').close();
  1830. });
  1831. // Re-calculate desktop height and width on window resize and re-position the login and signup windows
  1832. $(window).on("resize", function () {
  1833. // If host env is popup, don't continue because the popup window has its own resize requirements.
  1834. if (window.embedded_in_popup)
  1835. return;
  1836. const ratio = window.desktop_width / window.innerWidth;
  1837. window.desktop_height = window.innerHeight - window.toolbar_height - window.taskbar_height;
  1838. window.desktop_width = window.innerWidth;
  1839. // Re-center the login window
  1840. const top = $(".window-login").position()?.top;
  1841. const width = $(".window-login").width();
  1842. $(".window-login").css({
  1843. left: (window.desktop_width - width) / 2,
  1844. top: top / ratio,
  1845. });
  1846. // Re-center the create account window
  1847. const top2 = $(".window-signup").position()?.top;
  1848. const width2 = $(".window-signup").width();
  1849. $(".window-signup").css({
  1850. left: (window.desktop_width - width2) / 2,
  1851. top: top2 / ratio,
  1852. });
  1853. });