initgui.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  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('keydown', async function(e){
  1213. const focused_el = document.activeElement;
  1214. //-----------------------------------------------------------------------
  1215. // Shift+Delete (win)/ option+command+delete (Mac) key pressed
  1216. // Permanent delete bypassing trash after alert
  1217. //-----------------------------------------------------------------------
  1218. if((e.keyCode === 46 && e.shiftKey) || (e.altKey && e.metaKey && e.keyCode === 8)) {
  1219. let $selected_items = $(active_element).closest(`.item-container`).find(`.item-selected`);
  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. }
  1239. }
  1240. return false;
  1241. }
  1242. //-----------------------------------------------------------------------
  1243. // Delete (win)/ ctrl+delete (Mac) / cmd+delete (Mac) key pressed
  1244. // Permanent delete from trash after alert or move to trash
  1245. //-----------------------------------------------------------------------
  1246. if(e.keyCode === 46 || (e.keyCode === 8 && (e.ctrlKey || e.metaKey))) {
  1247. // permanent delete?
  1248. let $selected_items = $(active_element).closest(`.item-container`).find(`.item-selected[data-path^="${trash_path + '/'}"]`);
  1249. if($selected_items.length > 0){
  1250. const alert_resp = await UIAlert({
  1251. message: `Are you sure you want to permanently delete these items?`,
  1252. buttons:[
  1253. {
  1254. label: 'Delete',
  1255. type: 'primary',
  1256. },
  1257. {
  1258. label: 'Cancel'
  1259. },
  1260. ]
  1261. })
  1262. if((alert_resp) === 'Delete'){
  1263. for (let index = 0; index < $selected_items.length; index++) {
  1264. const element = $selected_items[index];
  1265. await delete_item(element);
  1266. }
  1267. const trash = await puter.fs.stat(trash_path);
  1268. if(window.socket){
  1269. window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
  1270. }
  1271. if(trash.is_empty){
  1272. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  1273. $(`.item[data-path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  1274. $(`.window[data-path="${html_encode(trash_path)}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  1275. }
  1276. }
  1277. }
  1278. // regular delete?
  1279. else{
  1280. $selected_items = $(active_element).closest('.item-container').find('.item-selected');
  1281. if($selected_items.length > 0){
  1282. // Only delete the items if we're not renaming one.
  1283. if ($selected_items.children('.item-name-editor-active').length === 0) {
  1284. move_items($selected_items, trash_path);
  1285. }
  1286. }
  1287. }
  1288. return false;
  1289. }
  1290. //-----------------------------------------------------------------------
  1291. // A letter or number is pressed and there is no context menu open: search items by name
  1292. //-----------------------------------------------------------------------
  1293. if(!e.ctrlKey && !e.metaKey && !$(focused_el).is('input') && !$(focused_el).is('textarea') && $('.context-menu').length === 0){
  1294. if(keypress_item_seach_term !== '')
  1295. clearTimeout(keypress_item_seach_buffer_timeout);
  1296. keypress_item_seach_buffer_timeout = setTimeout(()=>{
  1297. keypress_item_seach_term = '';
  1298. }, 700);
  1299. keypress_item_seach_term += e.key.toLocaleLowerCase();
  1300. let matches= [];
  1301. const selected_items = $(active_item_container).find(`.item-selected`).not('.item-disabled').first();
  1302. // if one item is selected and the selected item matches the search term, don't continue search and select this item again
  1303. if(selected_items.length === 1 && $(selected_items).attr('data-name').toLowerCase().startsWith(keypress_item_seach_term)){
  1304. return false;
  1305. }
  1306. // search for matches
  1307. let haystack = $(active_item_container).find(`.item`).not('.item-disabled');
  1308. for(let j=0; j < haystack.length; j++){
  1309. if($(haystack[j]).attr('data-name').toLowerCase().startsWith(keypress_item_seach_term)){
  1310. matches.push(haystack[j])
  1311. }
  1312. }
  1313. if(matches.length > 0){
  1314. // if there are multiple matches and an item is already selected, remove all matches before the selected item
  1315. if(selected_items.length > 0 && matches.length > 1){
  1316. let match_index;
  1317. for(let i=0; i < matches.length - 1; i++){
  1318. if($(matches[i]).is(selected_items)){
  1319. match_index = i;
  1320. break;
  1321. }
  1322. }
  1323. matches.splice(0, match_index+1);
  1324. }
  1325. // deselect all selected sibling items
  1326. $(active_item_container).find(`.item-selected`).removeClass('item-selected');
  1327. // select matching item
  1328. $(matches[0]).not('.item-disabled').addClass('item-selected');
  1329. matches[0].scrollIntoView(false);
  1330. update_explorer_footer_selected_items_count($(active_element).closest('.window'));
  1331. }
  1332. return false;
  1333. }
  1334. //-----------------------------------------------------------------------
  1335. // A letter or number is pressed and there is a context menu open: search items by name
  1336. //-----------------------------------------------------------------------
  1337. else if(!e.ctrlKey && !e.metaKey && !$(focused_el).is('input') && !$(focused_el).is('textarea') && $('.context-menu').length > 0){
  1338. if(keypress_item_seach_term !== '')
  1339. clearTimeout(keypress_item_seach_buffer_timeout);
  1340. keypress_item_seach_buffer_timeout = setTimeout(()=>{
  1341. keypress_item_seach_term = '';
  1342. }, 700);
  1343. keypress_item_seach_term += e.key.toLocaleLowerCase();
  1344. let matches= [];
  1345. const selected_items = $('.context-menu').find(`.context-menu-item-active`).first();
  1346. // if one item is selected and the selected item matches the search term, don't continue search and select this item again
  1347. if(selected_items.length === 1 && $(selected_items).text().toLowerCase().startsWith(keypress_item_seach_term)){
  1348. return false;
  1349. }
  1350. // search for matches
  1351. let haystack = $('.context-menu-active').find(`.context-menu-item`);
  1352. for(let j=0; j < haystack.length; j++){
  1353. if($(haystack[j]).text().toLowerCase().startsWith(keypress_item_seach_term)){
  1354. matches.push(haystack[j])
  1355. }
  1356. }
  1357. if(matches.length > 0){
  1358. // if there are multiple matches and an item is already selected, remove all matches before the selected item
  1359. if(selected_items.length > 0 && matches.length > 1){
  1360. let match_index;
  1361. for(let i=0; i < matches.length - 1; i++){
  1362. if($(matches[i]).is(selected_items)){
  1363. match_index = i;
  1364. break;
  1365. }
  1366. }
  1367. matches.splice(0, match_index+1);
  1368. }
  1369. // deselect all selected sibling items
  1370. $('.context-menu').find(`.context-menu-item-active`).removeClass('context-menu-item-active');
  1371. // select matching item
  1372. $(matches[0]).addClass('context-menu-item-active');
  1373. // matches[0].scrollIntoView(false);
  1374. // update_explorer_footer_selected_items_count($(active_element).closest('.window'));
  1375. }
  1376. return false;
  1377. }
  1378. })
  1379. $(document).bind("keyup keydown", async function(e){
  1380. const focused_el = document.activeElement;
  1381. //-----------------------------------------------------------------------------
  1382. // Override ctrl/cmd + s/o
  1383. //-----------------------------------------------------------------------------
  1384. if((e.ctrlKey || e.metaKey) && (e.which === 83 || e.which === 79)){
  1385. e.preventDefault()
  1386. return false;
  1387. }
  1388. //-----------------------------------------------------------------------------
  1389. // Select All
  1390. // ctrl/command + a, will select all items on desktop and windows
  1391. //-----------------------------------------------------------------------------
  1392. if((e.ctrlKey || e.metaKey) && e.which === 65 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1393. let $parent_container = $(active_element).closest('.item-container');
  1394. if($parent_container.length === 0)
  1395. $parent_container = $(active_element).find('.item-container');
  1396. if($parent_container.attr('data-multiselectable') === 'false')
  1397. return false;
  1398. if($parent_container){
  1399. $($parent_container).find('.item').not('.item-disabled').addClass('item-selected');
  1400. update_explorer_footer_selected_items_count($parent_container.closest('.window'));
  1401. }
  1402. return false;
  1403. }
  1404. //-----------------------------------------------------------------------------
  1405. // Close Window
  1406. // ctrl + w, will close the active window
  1407. //-----------------------------------------------------------------------------
  1408. if(e.ctrlKey && e.which === 87){
  1409. let $parent_window = $(active_element).closest('.window');
  1410. if($parent_window.length === 0)
  1411. $parent_window = $(active_element).find('.window');
  1412. if($parent_window !== null){
  1413. $($parent_window).close();
  1414. }
  1415. }
  1416. //-----------------------------------------------------------------------------
  1417. // Copy
  1418. // ctrl/command + c, will copy selected items on the active element to the clipboard
  1419. //-----------------------------------------------------------------------------
  1420. if((e.ctrlKey || e.metaKey) && e.which === 67 &&
  1421. $(mouseover_window).attr('data-is_dir') !== 'false' &&
  1422. $(mouseover_window).attr('data-path') !== trash_path &&
  1423. !$(focused_el).is('input') &&
  1424. !$(focused_el).is('textarea')){
  1425. let $selected_items;
  1426. let parent_container = $(active_element).closest('.item-container');
  1427. if(parent_container.length === 0)
  1428. parent_container = $(active_element).find('.item-container');
  1429. if(parent_container !== null){
  1430. $selected_items = $(parent_container).find('.item-selected');
  1431. if($selected_items.length > 0){
  1432. clipboard = [];
  1433. clipboard_op = 'copy';
  1434. $selected_items.each(function() {
  1435. // error if trash is being copied
  1436. if($(this).attr('data-path') === trash_path){
  1437. return;
  1438. }
  1439. // add to clipboard
  1440. clipboard.push({path: $(this).attr('data-path'), uid: $(this).attr('data-uid'), metadata: $(this).attr('data-metadata')});
  1441. })
  1442. }
  1443. }
  1444. return false;
  1445. }
  1446. //-----------------------------------------------------------------------------
  1447. // Cut
  1448. // ctrl/command + x, will copy selected items on the active element to the clipboard
  1449. //-----------------------------------------------------------------------------
  1450. if((e.ctrlKey || e.metaKey) && e.which === 88 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1451. let $selected_items;
  1452. let parent_container = $(active_element).closest('.item-container');
  1453. if(parent_container.length === 0)
  1454. parent_container = $(active_element).find('.item-container');
  1455. if(parent_container !== null){
  1456. $selected_items = $(parent_container).find('.item-selected');
  1457. if($selected_items.length > 0){
  1458. clipboard = [];
  1459. clipboard_op = 'move';
  1460. $selected_items.each(function() {
  1461. clipboard.push($(this).attr('data-path'));
  1462. })
  1463. }
  1464. }
  1465. return false;
  1466. }
  1467. //-----------------------------------------------------------------------
  1468. // Open
  1469. // Enter key on a selected item will open it
  1470. //-----------------------------------------------------------------------
  1471. if(e.which === 13 && !$(focused_el).is('input') && !$(focused_el).is('textarea') && (Date.now() - last_enter_pressed_to_rename_ts) >200
  1472. // prevent firing twice, because this will be fired on both keyup and keydown
  1473. && e.type === 'keydown'){
  1474. let $selected_items;
  1475. e.preventDefault();
  1476. e.stopPropagation();
  1477. // ---------------------------------------------
  1478. // if this is a selected Launch menu item, open it
  1479. // ---------------------------------------------
  1480. if($('.launch-app-selected').length > 0){
  1481. // close launch menu
  1482. $(".launch-popover").fadeOut(200, function(){
  1483. launch_app({
  1484. name: $('.launch-app-selected').attr('data-name'),
  1485. })
  1486. $(".launch-popover").remove();
  1487. });
  1488. return false;
  1489. }
  1490. // ---------------------------------------------
  1491. // if this is a selected context menu item, open it
  1492. // ---------------------------------------------
  1493. else if($('.context-menu-active .context-menu-item-active').length > 0 && (e.which === 13)){
  1494. // let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1495. // $(selected_item).trigger('mouseover');
  1496. // $(selected_item).trigger('click');
  1497. let selected_item = $('.context-menu-active .context-menu-item-active').get(0);
  1498. $(selected_item).removeClass('context-menu-item-active');
  1499. $(selected_item).addClass('context-menu-item-active-blurred');
  1500. $(selected_item).trigger('mouseover');
  1501. $(selected_item).trigger('click');
  1502. if($('.context-menu[data-is-submenu="true"]').length > 0){
  1503. let selected_item = $('.context-menu[data-is-submenu="true"] .context-menu-item').get(0);
  1504. select_ctxmenu_item(selected_item);
  1505. }
  1506. return false;
  1507. }
  1508. // ---------------------------------------------
  1509. // if this is a selected item, open it
  1510. // ---------------------------------------------
  1511. else if(active_item_container){
  1512. $selected_items = $(active_item_container).find('.item-selected');
  1513. if($selected_items.length > 0){
  1514. $selected_items.each(function() {
  1515. open_item({
  1516. item: this,
  1517. new_window: e.metaKey || e.ctrlKey,
  1518. });
  1519. })
  1520. }
  1521. return false;
  1522. }
  1523. return false;
  1524. }
  1525. //----------------------------------------------
  1526. // Paste
  1527. // ctrl/command + v, will paste items from the clipboard to the active element
  1528. //----------------------------------------------
  1529. if((e.ctrlKey || e.metaKey) && e.which === 86 && !$(focused_el).is('input') && !$(focused_el).is('textarea')){
  1530. let target_path, target_el;
  1531. // continue only if there is something in the clipboard
  1532. if(clipboard.length === 0)
  1533. return;
  1534. let parent_container = determine_active_container_parent();
  1535. if(parent_container){
  1536. target_el = parent_container;
  1537. target_path = $(parent_container).attr('data-path');
  1538. // don't allow pasting in Trash
  1539. if((target_path === trash_path || target_path.startsWith(trash_path + '/')) && clipboard_op !== 'move')
  1540. return;
  1541. // execute clipboard operation
  1542. if(clipboard_op === 'copy')
  1543. copy_clipboard_items(target_path);
  1544. else if(clipboard_op === 'move')
  1545. move_clipboard_items(target_el, target_path);
  1546. }
  1547. return false;
  1548. }
  1549. //-----------------------------------------------------------------------------
  1550. // Undo
  1551. // ctrl/command + z, will undo last action
  1552. //-----------------------------------------------------------------------------
  1553. if((e.ctrlKey || e.metaKey) && e.which === 90){
  1554. undo_last_action();
  1555. return false;
  1556. }
  1557. });
  1558. $(document).on('click', '.remove-permission-link', async function(e){
  1559. const el_remove_perm_link= this;
  1560. const perm_uid = $(el_remove_perm_link).attr('data-perm-uid');
  1561. $.ajax({
  1562. url: api_origin + "/remove-perm",
  1563. type: 'POST',
  1564. async: true,
  1565. contentType: "application/json",
  1566. data: JSON.stringify({
  1567. uid: perm_uid,
  1568. }),
  1569. headers: {
  1570. "Authorization": "Bearer "+auth_token
  1571. },
  1572. statusCode: {
  1573. 401: function () {
  1574. logout();
  1575. },
  1576. },
  1577. success: async function (res){
  1578. $(`[data-perm-uid="${perm_uid}"]`).hide("slide", { direction: "right" }, 300, function(e){
  1579. $(this).remove();
  1580. });
  1581. },
  1582. complete: function(){
  1583. }
  1584. })
  1585. })
  1586. // update mouse position coordinates
  1587. $(document).mousemove(function(event){
  1588. mouseX = event.clientX;
  1589. mouseY = event.clientY;
  1590. // mouse in top-left corner of screen
  1591. if((mouseX < 150 && mouseY < toolbar_height + 20) || (mouseX < 20 && mouseY < 150))
  1592. current_active_snap_zone = 'nw';
  1593. // mouse in left edge of screen
  1594. else if(mouseX < 20 && mouseY >= 150 && mouseY < desktop_height - 150)
  1595. current_active_snap_zone = 'w';
  1596. // mouse in bottom-left corner of screen
  1597. else if(mouseX < 20 && mouseY > desktop_height - 150)
  1598. current_active_snap_zone = 'sw';
  1599. // mouse in right edge of screen
  1600. else if(mouseX > desktop_width - 20 && mouseY >= 150 && mouseY < desktop_height - 150)
  1601. current_active_snap_zone = 'e';
  1602. // mouse in top-right corner of screen
  1603. else if((mouseX > desktop_width - 150 && mouseY < toolbar_height + 20) || (mouseX > desktop_width - 20 && mouseY < 150))
  1604. current_active_snap_zone = 'ne';
  1605. // mouse in bottom-right corner of screen
  1606. else if(mouseX > desktop_width - 20 && mouseY >= desktop_height - 150)
  1607. current_active_snap_zone = 'se';
  1608. // mouse in top edge of screen
  1609. else if(mouseY < toolbar_height + 20 && mouseX >= 150 && mouseX < desktop_width - 150)
  1610. current_active_snap_zone = 'n';
  1611. // not in any snap zone
  1612. else
  1613. current_active_snap_zone = undefined;
  1614. // mouseover_window
  1615. var windows = document.getElementsByClassName("window");
  1616. let active_win;
  1617. if(windows.length > 0){
  1618. let highest_window_zindex = 0;
  1619. for(let i=0; i<windows.length; i++){
  1620. const rect = windows[i].getBoundingClientRect();
  1621. if( mouseX > rect.x && mouseX < (rect.x + rect.width) && mouseY > rect.y && mouseY < (rect.y + rect.height)){
  1622. if(parseInt($(windows[i]).css('z-index')) >= highest_window_zindex){
  1623. active_win = windows[i];
  1624. highest_window_zindex = parseInt($(windows[i]).css('z-index'));
  1625. }
  1626. }
  1627. }
  1628. }
  1629. window.mouseover_window = active_win;
  1630. // mouseover_item_container
  1631. var item_containers = document.getElementsByClassName("item-container");
  1632. let active_ic;
  1633. if(item_containers.length > 0){
  1634. let highest_window_zindex = 0;
  1635. for(let i=0; i<item_containers.length; i++){
  1636. const rect = item_containers[i].getBoundingClientRect();
  1637. if( mouseX > rect.x && mouseX < (rect.x + rect.width) && mouseY > rect.y && mouseY < (rect.y + rect.height)){
  1638. let active_container_zindex = parseInt($(item_containers[i]).closest('.window').css('z-index'));
  1639. if( !isNaN(active_container_zindex) && active_container_zindex >= highest_window_zindex){
  1640. active_ic = item_containers[i];
  1641. highest_window_zindex = active_container_zindex;
  1642. }
  1643. }
  1644. }
  1645. }
  1646. window.mouseover_item_container = active_ic;
  1647. });
  1648. //--------------------------------------------------------
  1649. // Window Activation
  1650. //--------------------------------------------------------
  1651. $(document).on('mousedown', function(e){
  1652. // if taskbar or any parts of it is clicked, drop the event
  1653. if($(e.target).hasClass('taskbar') || $(e.target).closest('.taskbar').length > 0)
  1654. return;
  1655. // if mouse is clicked on a window, activate it
  1656. if(mouseover_window !== undefined){
  1657. $(mouseover_window).focusWindow(e);
  1658. }
  1659. })
  1660. // if an element has the .long-hover class, fire a long-hover event after 600ms
  1661. $(document).on('mouseenter', '.long-hover', function(){
  1662. let el = this;
  1663. el.long_hover_timeout = setTimeout(() => {
  1664. $(el).trigger('long-hover');
  1665. }, 600);
  1666. })
  1667. // if an element has the .long-hover class, cancel the long-hover event if the mouse leaves
  1668. $(document).on('mouseleave', '.long-hover', function(){
  1669. clearTimeout(this.long_hover_timeout);
  1670. })
  1671. // if an element has the .long-hover class, cancel the long-hover event if the mouse leaves
  1672. $(document).on('paste', function(event){
  1673. event = event.originalEvent ?? event;
  1674. let clipboardData = event.clipboardData || window.clipboardData;
  1675. let items = clipboardData.items || clipboardData.files;
  1676. // return if paste is on input or textarea
  1677. if($(event.target).is('input') || $(event.target).is('textarea'))
  1678. return;
  1679. if(!(items instanceof DataTransferItemList))
  1680. return;
  1681. // upload files
  1682. if(items?.length>0){
  1683. let parent_container = determine_active_container_parent();
  1684. if(parent_container){
  1685. upload_items(items, $(parent_container).attr('data-path'));
  1686. }
  1687. }
  1688. event.stopPropagation();
  1689. event.preventDefault();
  1690. return false;
  1691. })
  1692. document.addEventListener("visibilitychange", (event) => {
  1693. if (document.visibilityState !== "visible") {
  1694. window.doc_title_before_blur = document.title;
  1695. if(!_.isEmpty(window.active_uploads)){
  1696. update_title_based_on_uploads();
  1697. }
  1698. }else if(window.active_uploads){
  1699. document.title = window.doc_title_before_blur ?? 'Puter';
  1700. }
  1701. });
  1702. /**
  1703. * Event handler for a custom 'logout' event attached to the document.
  1704. * This function handles the process of logging out, including user confirmation,
  1705. * communication with the backend, and subsequent UI updates. It takes special
  1706. * precautions if the user is identified as using a temporary account.
  1707. *
  1708. * @listens Document#event:logout
  1709. * @async
  1710. * @param {Event} event - The JQuery event object associated with the logout event.
  1711. * @returns {Promise<void>} - This function does not return anything meaningful, but it performs an asynchronous operation.
  1712. */
  1713. $(document).on("logout", async function(event) {
  1714. // is temp user?
  1715. if(window.user && window.user.is_temp){
  1716. const alert_resp = await UIAlert({
  1717. message: `<strong>Save account before logging out!</strong><p>You are using a temporary account and logging out will erase all your data.</p>`,
  1718. buttons:[
  1719. {
  1720. label: 'Save Account',
  1721. type: 'primary',
  1722. },
  1723. {
  1724. label: 'Log Out',
  1725. type: 'danger',
  1726. },
  1727. {
  1728. label: 'Cancel',
  1729. },
  1730. ]
  1731. })
  1732. if(alert_resp === 'Save Account'){
  1733. let saved = await UIWindowSaveAccount({
  1734. send_confirmation_code: false,
  1735. default_username: window.user.username
  1736. });
  1737. if(saved)
  1738. logout();
  1739. }else if (alert_resp === 'Log Out'){
  1740. logout();
  1741. }
  1742. else{
  1743. return;
  1744. }
  1745. }
  1746. // logout
  1747. try{
  1748. await $.ajax({
  1749. url: gui_origin + "/logout",
  1750. type: 'POST',
  1751. async: true,
  1752. contentType: "application/json",
  1753. headers: {
  1754. "Authorization": "Bearer " + auth_token
  1755. },
  1756. statusCode: {
  1757. 401: function () {
  1758. },
  1759. },
  1760. })
  1761. }catch(e){
  1762. }
  1763. // remove this user from the array of logged_in_users
  1764. for (let i = 0; i < window.logged_in_users.length; i++) {
  1765. if(window.logged_in_users[i].uuid === window.user.uuid){
  1766. window.logged_in_users.splice(i, 1);
  1767. break;
  1768. }
  1769. }
  1770. // update logged_in_users in local storage
  1771. localStorage.setItem('logged_in_users', JSON.stringify(window.logged_in_users));
  1772. // delete this user from local storage
  1773. window.user = null;
  1774. localStorage.removeItem('user');
  1775. window.auth_token = null;
  1776. localStorage.removeItem('auth_token');
  1777. // close all windows
  1778. $('.window').close();
  1779. // close all ctxmenus
  1780. $('.context-menu').remove();
  1781. // remove desktop
  1782. $('.desktop').remove();
  1783. // remove taskbar
  1784. $('.taskbar').remove();
  1785. // disable native browser exit confirmation
  1786. window.onbeforeunload = null;
  1787. // go to home page
  1788. window.location.replace("/");
  1789. });
  1790. }
  1791. function requestOpenerOrigin() {
  1792. return new Promise((resolve, reject) => {
  1793. if (!window.opener) {
  1794. reject(new Error("No window.opener available"));
  1795. return;
  1796. }
  1797. // Function to handle the message event
  1798. const handleMessage = (event) => {
  1799. // Check if the message is the expected response
  1800. if (event.data.msg === 'originResponse') {
  1801. // Clean up by removing the event listener
  1802. window.removeEventListener('message', handleMessage);
  1803. resolve(event.origin);
  1804. }
  1805. };
  1806. // Set up the listener for the response
  1807. window.addEventListener('message', handleMessage, false);
  1808. // Send the request to the opener
  1809. window.opener.postMessage({ msg: 'requestOrigin' }, '*');
  1810. // Optional: Reject the promise if no response is received within a timeout
  1811. setTimeout(() => {
  1812. window.removeEventListener('message', handleMessage);
  1813. reject(new Error("Response timed out"));
  1814. }, 5000); // Timeout after 5 seconds
  1815. });
  1816. }
  1817. $(document).on('click', '.generic-close-window-button', function(e){
  1818. $(this).closest('.window').close();
  1819. });