initgui.js 92 KB

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