-
Notifications
You must be signed in to change notification settings - Fork 0
/
appUtil.m
394 lines (323 loc) · 17.6 KB
/
appUtil.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
classdef (Abstract) appUtil
methods (Static = true)
%-----------------------------------------------------------------%
function disablingWarningMessages()
warning('off', 'MATLAB:ui:javaframe:PropertyToBeRemoved')
warning('off', 'MATLAB:subscripting:noSubscriptsSpecified')
warning('off', 'MATLAB:structOnObject')
warning('off', 'MATLAB:class:DestructorError')
warning('off', 'MATLAB:modes:mode:InvalidPropertySet')
warning('off', 'MATLAB:table:RowsAddedExistingVars')
warning('off', 'MATLAB:colon:operandsNotRealScalar')
warning('off', 'MATLAB:opengl:unableToSelectHWGL')
end
%-----------------------------------------------------------------%
function executionMode = ExecutionMode(hFigure)
% No MATLAB R2024, os containeres das versões desktop e webapp
% de um app são os arquivos "cefComponentContainer.html" e
% "webAppsComponentContainer.html", respectivamente.
% >> struct(struct(hFigure).Controller).PeerModelInfo.URL
% 'https://127.0.0.1:31517/toolbox/matlab/uitools/uifigureappjs/cefComponentContainer.html?channel=/uifigure/45562d91-459d-4a9e-bafc-4f51c6940e09&websocket=on&syncMode=MF0ViewModel&snc=FV5YKZ' (MATLAB)
% 'https://127.0.0.1:31517/toolbox/matlab/uitools/uifigureappjs/cefComponentContainer.html?channel=/uifigure/04fb3193-a2cb-405a-9eac-8e3e38486454&websocket=on&syncMode=MF0ViewModel&snc=JOZ8GB' (MATLAB Runtime)
% 'http://df6963612dtn:9988/services/static/24.1/toolbox/compiler/mdwas/client/session/webAppContainer.html?MDWAS-Connection-Id=5d9ffe85-3824-419b-bedb-1ad678c5ac4b' (MATLAB WebServer - DEPLOY)
% 'https://fiscalizacao.anatel.gov.br/services/static/24.1/toolbox/compiler/mdwas/client/session/webAppContainer.html?MDWAS-Connection-Id=2240b1cf-15c0-4894-9ee0-6b52508f1b44' (MATLAB WebServer)
% >> struct(struct(struct(hFigure).Controller).PlatformHost).ReleaseHTMLFile
% 'cefComponentContainer.html' (MATLAB, e MATLAB Runtime)
% 'webAppsComponentContainer.html' (MATLAB WebServer)
htmlAppContainer = struct(struct(struct(hFigure).Controller).PlatformHost).ReleaseHTMLFile;
if contains(htmlAppContainer, 'webApp', 'IgnoreCase', true)
executionMode = 'webApp';
else
if isdeployed
executionMode = 'desktopStandaloneApp';
else
executionMode = 'MATLABEnvironment';
end
end
end
%-----------------------------------------------------------------%
function rootFolder = RootFolder(appName, MFilePath)
rootFolder = MFilePath;
if isdeployed
[status, executionFolder] = ccTools.fcn.OperationSystem('desktopStandaloneAppFolder', appName);
if status
rootFolder = executionFolder;
end
end
end
%-----------------------------------------------------------------%
function killingMATLABRuntime(executionMode)
if ismember(executionMode, {'desktopStandaloneApp', 'webapp'})
pidMatlab = feature('getpid');
system(sprintf('taskkill /F /PID %d', pidMatlab));
end
end
%-----------------------------------------------------------------%
function winPosition(hFigure)
[xPosition, yPosition] = appUtil.winXYPosition(hFigure.Position(3), hFigure.Position(4));
hFigure.Position(1:2) = [xPosition, yPosition];
end
%-----------------------------------------------------------------%
function [xPosition, yPosition] = winXYPosition(figWidth, figHeight)
mainMonitor = get(0, 'MonitorPositions');
[~, idx] = max(mainMonitor(:,3));
mainMonitor = mainMonitor(idx,:);
xPosition = mainMonitor(1)+round((mainMonitor(3)-figWidth)/2);
yPosition = mainMonitor(2)+round((mainMonitor(4)+18-figHeight)/2);
end
%-----------------------------------------------------------------%
function winMinSize(hFigure, minSize)
try
webWin = struct(struct(struct(hFigure).Controller).PlatformHost).CEF;
webWin.setMinSize(minSize)
catch
end
end
%-----------------------------------------------------------------%
function htmlSource = jsBackDoorHTMLSource()
htmlSource = fullfile(fileparts(mfilename('fullpath')), 'jsBackDoor', 'Container.html');
end
%-----------------------------------------------------------------%
function [fileFullName, fileName] = DefaultFileName(filePath, Prefix, Suffix)
arguments
filePath char
Prefix string
Suffix string = ''
end
fileName = sprintf('%s_%s', Prefix, datestr(now, 'yyyy.mm.dd_THH.MM.SS'));
if Suffix ~= "-1"
fileName = sprintf('%s_%s', fileName, Suffix);
end
fileFullName = fullfile(filePath, fileName);
end
%-----------------------------------------------------------------%
function varargout = modalWindow(hFigure, type, msg, varargin)
arguments
hFigure matlab.ui.Figure
type {mustBeMember(type, {'error', 'warning', 'info', 'progressdlg', 'uiconfirm', 'uigetfile', 'uiputfile'})}
msg {mustBeTextScalar} = ''
end
arguments (Repeating)
varargin
end
if ~isempty(msg)
msg = textFormatGUI.HTMLParagraph(msg);
end
switch type
case {'error', 'warning', 'info'}
switch type
case 'error'; uialert(hFigure, msg, '', 'Interpreter', 'html', 'Icon', 'error', varargin{:})
case 'warning'; uialert(hFigure, msg, '', 'Interpreter', 'html', 'Icon', 'warning', varargin{:})
case 'info'; uialert(hFigure, msg, '', 'Interpreter', 'html', 'Icon', 'info', varargin{:})
end
varargout = {[]};
beep
case 'progressdlg'
dlg = uiprogressdlg(hFigure, 'Indeterminate', 'on', 'Interpreter', 'html', 'Message', msg, varargin{:});
varargout{1} = dlg;
case 'uiconfirm'
if isscalar(varargin{1})
Icon = 'warning';
else
Icon = 'question';
end
userSelection = uiconfirm(hFigure, msg, '', 'Options', varargin{1}, 'DefaultOption', varargin{2}, 'CancelOption', varargin{3}, 'Interpreter', 'html', 'Icon', Icon);
varargout{1} = userSelection;
case 'uigetfile'
fileFormats = varargin{1};
lastVisitedFolder = varargin{2};
otherParameters = {};
if nargin == 6
otherParameters = varargin{3};
end
[fileName, fileFolder] = uigetfile(fileFormats, '', lastVisitedFolder, otherParameters{:});
figure(hFigure)
if isequal(fileName, 0)
varargout = {[], [], [], []};
return
end
fileFullPath = fullfile(fileFolder, fileName);
[~, ~, fileExt] = fileparts(fileName);
varargout = {fileFullPath, fileFolder, lower(fileExt), fileName};
case 'uiputfile'
nameFormatMap = varargin{1};
defaultFilename = varargin{2};
[fileName, fileFolder] = uiputfile(nameFormatMap, '', defaultFilename);
figure(hFigure)
if isequal(fileName, 0)
varargout = {[], [], [], []};
return
end
fileFullPath = fullfile(fileFolder, fileName);
[~, ~, fileExt] = fileparts(fileName);
varargout = {fileFullPath, fileFolder, lower(fileExt), fileName};
end
end
%-----------------------------------------------------------------%
function hPanel = modalDockContainer(jsBackDoor, containerType, varargin)
arguments
jsBackDoor (1,1) matlab.ui.control.HTML
containerType char {mustBeMember(containerType, {'Popup', 'Popup+CloseButton'})} = 'Popup'
end
arguments (Repeating)
varargin
end
switch containerType
case 'Popup'
Padding = varargin{1};
winWidth = varargin{2};
winHeight = varargin{3};
hFigure = ancestor(jsBackDoor, 'figure');
hGrid = uigridlayout(hFigure, ColumnWidth={'1x', winWidth, '1x'}, RowHeight={'1x', winHeight, '1x'}, Padding=Padding*[1,1,1,1], ColumnSpacing=0, RowSpacing=0);
hPanel = uipanel(hGrid, Title='', AutoResizeChildren='off');
hPanel.Layout.Row = 2;
hPanel.Layout.Column = 2;
drawnow
ccTools.compCustomizationV2(jsBackDoor, hGrid, 'backgroundColor', 'rgba(255,255,255,0.65)')
hPanelDataTag = struct(hPanel).Controller.ViewModel.Id;
sendEventToHTMLSource(jsBackDoor, "panelDialog", struct('componentDataTag', hPanelDataTag))
case 'Popup+CloseButton'
Padding = varargin{1};
hFigure = ancestor(jsBackDoor, 'figure');
hGrid = uigridlayout(hFigure, ColumnWidth={'1x', 16}, RowHeight={20, '1x'}, Padding=Padding*[1,1,1,1], ColumnSpacing=0, RowSpacing=0);
hPanel = uipanel(hGrid, Title='', AutoResizeChildren='off');
hPanel.Layout.Row = [1,2];
hPanel.Layout.Column = [1,2];
hImage = uiimage(hGrid, ImageSource='Delete_32Gray.png');
hImage.Layout.Row = 1;
hImage.Layout.Column = 2;
drawnow
ccTools.compCustomizationV2(jsBackDoor, hGrid, 'backgroundColor', 'rgba(255,255,255,0.65)')
end
hPanel.DeleteFcn = @(~,~)DeleteModalContainer();
function DeleteModalContainer()
delete(hGrid)
end
end
%-----------------------------------------------------------------%
function [projectFolder, programDataFolder] = Path(appName, rootFolder)
projectFolder = fullfile(rootFolder, 'Settings');
programDataFolder = fullfile(ccTools.fcn.OperationSystem('programData'), 'ANATEL', appName);
end
%-----------------------------------------------------------------%
function userPaths = UserPaths(userPath)
userPaths = [ccTools.fcn.OperationSystem('userPath'), {userPath}];
userPaths(~isfolder(userPaths)) = [];
if isempty(userPaths)
tempFolder = tempname;
if ~isfolder(tempFolder)
mkdir(tempFolder)
end
userPaths = {tempFolder};
end
end
%-----------------------------------------------------------------%
function [generalSettings, msgWarning] = generalSettingsLoad(appName, rootFolder, files2Keep)
% Para melhor controle das customizações de operação dos apps, os arquivos
% de configuração serão armazenados em pasta %PROGRAMDATA%\ANATEL\%appName%
%
% Caso a pasta não exista, o app a criará no seu processo de inicialização,
% copiando os arquivos de configuração do projeto, originalmente armazenados
% na subpasta "Settings" do projeto.
%
% Caso a pasta exista, por outro lado, verifica-se a versão do arquivo
% "GeneralSettings.json".
arguments
appName char
rootFolder char
files2Keep cell = {}
end
generalSettings = [];
msgWarning = '';
[projectFolder, ...
programDataFolder] = appUtil.Path(appName, rootFolder);
projectFilePath = fullfile(projectFolder, 'GeneralSettings.json');
programDataFilePath = fullfile(programDataFolder, 'GeneralSettings.json');
projectFileContent = jsondecode(fileread(projectFilePath));
try
if ~isfile(programDataFilePath)
if ~isfolder(programDataFolder)
mkdir(programDataFolder)
end
appUtil.copyConfigFiles(projectFolder, programDataFolder)
else
programDataFileContent = jsondecode(fileread(programDataFilePath));
if projectFileContent.version > programDataFileContent.version
oldFields = fieldnames(programDataFileContent.fileFolder);
for ii = 1:numel(oldFields)
if isfield(projectFileContent.fileFolder, oldFields{ii})
projectFileContent.fileFolder.(oldFields{ii}) = programDataFileContent.fileFolder.(oldFields{ii});
end
end
programDataFolder_backup = fullfile(programDataFolder, 'oldFiles');
if ~isfolder(programDataFolder_backup)
mkdir(programDataFolder_backup)
end
appUtil.copyConfigFiles(programDataFolder, programDataFolder_backup, files2Keep)
appUtil.copyConfigFiles(projectFolder, programDataFolder)
writematrix(jsonencode(projectFileContent, "PrettyPrint", true), programDataFilePath, "FileType", "text", "QuoteStrings", "none", "WriteMode", "overwrite")
msgWarning = ['Os arquivos de configuração do app hospedado na pasta de configuração local, ' ...
'incluindo "GeneralSettings.json", foram atualizados. As versões antigas dos ' ...
'arquivos foram salvas na subpasta "oldFiles".'];
else
generalSettings = programDataFileContent;
end
end
catch ME
msgWarning = ME.message;
end
if isempty(generalSettings)
generalSettings = projectFileContent;
end
if ~isempty(generalSettings.fileFolder.lastVisited) && ~isfolder(generalSettings.fileFolder.lastVisited)
generalSettings.fileFolder.lastVisited = '';
end
end
%-------------------------------------------------------------------------%
function generalSettingsSave(appName, rootFolder, appGeneral, executionMode, fields2Remove)
% Aplicável apenas à versão desktop do app. Dessa forma, o parâmetro
% de configuração alterado por um usuário do webapp terá efeito apenas
% na própria sessão do webapp.
arguments
appName char
rootFolder char
appGeneral struct
executionMode char
fields2Remove cell = {}
end
if strcmp(executionMode, 'webApp')
return
end
if ~isempty(fields2Remove)
appGeneral = rmfield(appGeneral, fields2Remove);
end
appGeneral.fileFolder.tempPath = '';
[~, ...
programDataFolder] = appUtil.Path(appName, rootFolder);
programDataFilePath = fullfile(programDataFolder, 'GeneralSettings.json');
try
writematrix(jsonencode(appGeneral, 'PrettyPrint', true), programDataFilePath, "FileType", "text", "QuoteStrings", "none", "WriteMode", "overwrite")
catch
end
end
end
methods (Access = private, Static = true)
%-------------------------------------------------------------------------%
function copyConfigFiles(oldPath, newPath, files2Keep)
arguments
oldPath char
newPath char
files2Keep cell = {}
end
cfgFiles = dir(oldPath);
cfgFiles([cfgFiles.isdir]) = [];
if ~isempty(files2Keep)
cfgFiles(cellfun(@(x) any(strcmpi(x, files2Keep)), {cfgFiles.name})) = [];
end
for ii = 1:numel(cfgFiles)
jsonFilePath = fullfile(cfgFiles(ii).folder, cfgFiles(ii).name);
copyfile(jsonFilePath, newPath, 'f');
end
end
end
end