1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 package com.sun.star.wizards.web;
24 
25 import javax.swing.ListModel;
26 
27 import com.sun.star.awt.KeyEvent;
28 import com.sun.star.awt.XControl;
29 import com.sun.star.awt.XKeyListener;
30 import com.sun.star.awt.XWindow;
31 import com.sun.star.container.NoSuchElementException;
32 import com.sun.star.lang.EventObject;
33 import com.sun.star.lang.XMultiServiceFactory;
34 import com.sun.star.uno.UnoRuntime;
35 import com.sun.star.util.XCloseable;
36 import com.sun.star.wizards.common.Configuration;
37 import com.sun.star.wizards.common.FileAccess;
38 import com.sun.star.wizards.common.Helper;
39 import com.sun.star.wizards.common.JavaTools;
40 import com.sun.star.wizards.common.SystemDialog;
41 import com.sun.star.wizards.common.PropertyNames;
42 import com.sun.star.wizards.ui.UnoDialog;
43 import com.sun.star.wizards.ui.event.DataAware;
44 import com.sun.star.wizards.ui.event.ListModelBinder;
45 import com.sun.star.wizards.ui.event.Task;
46 import com.sun.star.wizards.web.data.CGDocument;
47 import com.sun.star.wizards.web.data.CGPublish;
48 import com.sun.star.wizards.web.data.CGSession;
49 import com.sun.star.wizards.web.data.CGSessionName;
50 
51 /**
52  * This class implements the ui-events of the
53  * web wizard.
54  * it is therfore sorted to steps.
55  * not much application-logic here - just plain
56  * methods which react to events.
57  * The only exception are the finish methods with the save
58  * session methods.
59  */
60 public abstract class WWD_Events extends WWD_Startup
61 {
62 
63     private static final short[] EMPTY_SHORT_ARRAY = new short[0];
64     /**
65      * Tracks the current loaded session.
66      * If PropertyNames.EMPTY_STRING - it means the current session is the default one (empty)
67      * If a session is loaded, this will be the name of the loaded session.
68      */
69     protected String currentSession = PropertyNames.EMPTY_STRING;
70 
71     /**
72      * He - my constructor !
73      * I add a window listener, which, when
74      * the window closes, deltes the temp directory.
75      */
WWD_Events(XMultiServiceFactory xmsf)76     public WWD_Events(XMultiServiceFactory xmsf) throws Exception
77     {
78         super(xmsf);
79         Create c = new Create();
80         XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, chkFTP);
81         xWindow.addKeyListener(c);
82         xWindow = UnoRuntime.queryInterface(XWindow.class, chkLocalDir);
83         xWindow.addKeyListener(c);
84         xWindow = UnoRuntime.queryInterface(XWindow.class, chkZip);
85         xWindow.addKeyListener(c);
86     }
87 
88     /* *********************************************************
89      *  *******************************************************
90      *          EVENT and UI METHODS
91      *  *******************************************************
92      * *********************************************************/
leaveStep(int nOldStep, int nNewStep)93     protected void leaveStep(int nOldStep, int nNewStep)
94     {
95         if (nOldStep == 1 && nNewStep == 2)
96         {
97             // 1. check if the selected session is the same as the current one.
98         }
99     }
100 
enterStep(int old, int newStep)101     protected void enterStep(int old, int newStep)
102     {
103         if ((old == 1))
104         {
105             String sessionToLoad = PropertyNames.EMPTY_STRING;
106             short[] s = (short[]) Helper.getUnoPropertyValue(getModel(lstLoadSettings), PropertyNames.SELECTED_ITEMS);
107             if (s.length == 0 || s[0] == 0)
108             {
109                 sessionToLoad = PropertyNames.EMPTY_STRING;
110             }
111             else
112             {
113                 sessionToLoad = ((CGSessionName) settings.cp_SavedSessions.getElementAt(s[0])).cp_Name;
114             }
115             if (!sessionToLoad.equals(currentSession))
116             {
117                 loadSession(sessionToLoad);
118             }
119         }
120         if (newStep == 5)
121         {
122         }
123     }
124 
125     /* *********************************
126      *  STEP 1
127      */
128     /**
129      * Called from the Uno event dispatcher when the
130      * user selects a saved session.
131      */
sessionSelected()132     public void sessionSelected()
133     {
134         short[] s = (short[]) Helper.getUnoPropertyValue(getModel(lstLoadSettings), PropertyNames.SELECTED_ITEMS);
135         setEnabled(btnDelSession, s.length > 0 && s[0] > 0);
136     }
137 
138     /**
139      * Ha ! the session should be loaded :-)
140      */
loadSession(final String sessionToLoad)141     public void loadSession(final String sessionToLoad)
142     {
143         try
144         {
145             final StatusDialog sd = getStatusDialog();
146 
147             final Task task = new Task("LoadDocs", PropertyNames.EMPTY_STRING, 10);
148 
149             sd.execute(this, task, resources.resLoadingSession);
150             task.start();
151 
152             setSelectedDoc(EMPTY_SHORT_ARRAY);
153             Helper.setUnoPropertyValue(getModel(lstDocuments), PropertyNames.SELECTED_ITEMS, EMPTY_SHORT_ARRAY);
154             Helper.setUnoPropertyValue(getModel(lstDocuments), PropertyNames.STRING_ITEM_LIST, EMPTY_STRING_ARRAY);
155 
156             Object view = null;
157 
158             if (sessionToLoad.equals(PropertyNames.EMPTY_STRING))
159             {
160                 view = Configuration.getConfigurationRoot(xMSF, CONFIG_PATH + "/DefaultSession", false);
161             }
162             else
163             {
164                 view = Configuration.getConfigurationRoot(xMSF, CONFIG_PATH + "/SavedSessions", false);
165                 view = Configuration.getNode(sessionToLoad, view);
166             }
167 
168             CGSession session = new CGSession();
169             session.setRoot(settings);
170             session.readConfiguration(view, CONFIG_READ_PARAM);
171             task.setMax(session.cp_Content.cp_Documents.getSize() * 5 + 7);
172             task.advance(true);
173 
174             if (sessionToLoad.equals(PropertyNames.EMPTY_STRING))
175             {
176                 setSaveSessionName(session);
177             }
178             mount(session, task, false, sd.xControl);
179 
180             checkSteps();
181             currentSession = sessionToLoad;
182 
183             while (task.getStatus() <= task.getMax())
184             {
185                 task.advance(false);
186             }
187             task.removeTaskListener(sd);
188         }
189         catch (Exception ex)
190         {
191             unexpectedError(ex);
192         }
193 
194         try
195         {
196             refreshStylePreview();
197             updateIconsetText();
198         }
199         catch (Exception e)
200         {
201             // TODO Auto-generated catch block
202             e.printStackTrace();
203         }
204     }
205 
206     /**
207      * hmm. the user clicked the delete button.
208      */
delSession()209     public void delSession()
210     {
211         short[] selected = (short[]) Helper.getUnoPropertyValue(getModel(lstLoadSettings), PropertyNames.SELECTED_ITEMS);
212         if (selected.length == 0)
213         {
214             return;
215         }
216         if (selected[0] == 0)
217         {
218             return;
219         }
220         boolean confirm = AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), resources.resDelSessionConfirm, ErrorHandler.ERROR_QUESTION_NO);
221         if (confirm)
222         {
223             try
224             {
225                 String name = (String) settings.cp_SavedSessions.getKey(selected[0]);
226                 // first delete the session from the registry/configuration.
227 
228                 Configuration.removeNode(xMSF, CONFIG_PATH + "/SavedSessions", name);
229 
230                 // then delete the session from the java-set (settings.cp_SavedSessions)
231                 settings.cp_SavedSessions.remove(selected[0]);
232                 settings.savedSessions.remove(selected[0] - 1);
233 
234                 short[] nextSelected = new short[]
235                 {
236                     (short) 0
237                 };
238                 // We try to select the same item index again, if possible
239                 if (settings.cp_SavedSessions.getSize() > selected[0])
240                 {
241                     nextSelected[0] = selected[0];
242                 }
243                 else
244                 // this will always be available because
245                 // the user can not remove item 0.
246                 {
247                     nextSelected[0] = (short) (selected[0] - 1);                // if the <none> session will be selected, disable the remove button...
248                 }
249                 if (nextSelected[0] == 0)
250                 {
251                     Helper.setUnoPropertyValue(getModel(btnDelSession), PropertyNames.PROPERTY_ENABLED, Boolean.FALSE);                // select...
252                 }
253                 Helper.setUnoPropertyValue(getModel(lstLoadSettings), PropertyNames.SELECTED_ITEMS, nextSelected);
254 
255             //ListModelBinder.fillComboBox(cbSaveSettings, settings.savedSessions.items(), null);
256 
257 
258             }
259             catch (Exception ex)
260             {
261                 ex.printStackTrace();
262                 unexpectedError(ex);
263             }
264         }
265     }
266 
267     /* ********************************
268      * STEP 2
269      */
270     /**
271      * A method used by the UnoDataAware attached
272      * to the Documents listbox.
273      * See the concept of the DataAware objects to undestand
274      * why it is there...
275      */
getSelectedDoc()276     public short[] getSelectedDoc()
277     {
278         return selectedDoc;
279     }
280     private static String[] EMPTY_STRING_ARRAY = new String[0];
281 
282     /*  public void loadSessionSelected() {
283     UIHelper.setEnabled(btnLoadSession,true);
284     UIHelper.setEnabled(btnDelSession,true);
285     }
286      */
287     /**
288      * when the user clicks another document
289      * in the listbox, this method is called,
290      * and couses the display in
291      * the textboxes title,description, author and export format
292      * to change
293      */
setSelectedDoc(short[] s)294     public void setSelectedDoc(short[] s)
295     {
296         CGDocument oldDoc = getDoc(selectedDoc);
297         CGDocument doc = getDoc(s);
298 
299         if (doc == null)
300         {
301             fillExportList(EMPTY_STRING_ARRAY);
302         //I try to avoid refreshing the export list if
303         //the same type of document is chosen.
304         }
305         else if (oldDoc == null || (!oldDoc.appType.equals(doc.appType)))
306         {
307             fillExportList(settings.getExporters(doc.appType));
308         }
309 
310 
311         selectedDoc = s;
312 
313         mount(doc, docAware);
314         disableDocUpDown();
315     }
316 
317     /**
318      * The user clicks the "Add" button.
319      * This will open a "FileOpen" dialog,
320      * and, if the user chooses more than one file,
321      * will open a status dialog, when validating each document.
322      */
addDocument()323     public void addDocument()
324     {
325 
326         final String[] files = getDocAddDialog().callOpenDialog(true, settings.cp_DefaultSession.cp_InDirectory);
327         if (files == null)
328         {
329             return;
330         }
331         final Task task = new Task(PropertyNames.EMPTY_STRING, PropertyNames.EMPTY_STRING, files.length * 5);
332 
333         /*
334          * If more than a certain number
335          * of documents have been added,
336          * open the status dialog.
337          */
338         if (files.length > MIN_ADD_FILES_FOR_DIALOG)
339         {
340             StatusDialog sd = getStatusDialog();
341             sd.setLabel(resources.resValidatingDocuments);
342             sd.execute(this, task, resources.prodName); // new LoadDocs( sd.xControl, files, task )
343             LoadDocs oLoadDocs = new LoadDocs(this.xControl, files, task);
344             oLoadDocs.loadDocuments();
345             task.removeTaskListener(sd);
346         }
347         /*
348          * When adding a single document, do not use a
349          * status dialog...
350          */
351         else
352         {
353             LoadDocs oLoadDocs = new LoadDocs(this.xControl, files, task);
354             oLoadDocs.loadDocuments();
355         }
356 
357     }
358 
359     /**
360      * The user clicked delete.
361      */
removeDocument()362     public void removeDocument()
363     {
364         if (selectedDoc.length == 0)
365         {
366             return;
367         }
368         settings.cp_DefaultSession.cp_Content.cp_Documents.remove(selectedDoc[0]);
369 
370         // update the selected document
371         while (selectedDoc[0] >= getDocsCount())
372         {
373             selectedDoc[0]--;        // if there are no documents...
374         }
375         if (selectedDoc[0] == -1)
376         {
377             selectedDoc = EMPTY_SHORT_ARRAY;        // update the list to show the right selection.
378         }
379         docListDA.updateUI();
380         // disables all the next steps, if the list of docuemnts
381         // is empty.
382         checkSteps();
383     }
384 
385     /**
386      * doc up.
387      */
docUp()388     public void docUp()
389     {
390         Object doc = settings.cp_DefaultSession.cp_Content.cp_Documents.getElementAt(selectedDoc[0]);
391         settings.cp_DefaultSession.cp_Content.cp_Documents.remove(selectedDoc[0]);
392         settings.cp_DefaultSession.cp_Content.cp_Documents.add(--selectedDoc[0], doc);
393         docListDA.updateUI();
394         disableDocUpDown();
395     }
396 
397     /**
398      * doc down
399      */
docDown()400     public void docDown()
401     {
402         Object doc = settings.cp_DefaultSession.cp_Content.cp_Documents.getElementAt(selectedDoc[0]);
403         settings.cp_DefaultSession.cp_Content.cp_Documents.remove(selectedDoc[0]);
404         settings.cp_DefaultSession.cp_Content.cp_Documents.add(++selectedDoc[0], doc);
405         docListDA.updateUI();
406         disableDocUpDown();
407     }
408 
409     /* ******************************
410      * STEP 5
411      */
412     /**
413      * invoked when the user clicks "Choose backgrounds" button.
414      */
415     private ImageListDialog bgDialog;
416 
417     /**
418      * the user clicked the "backgrounds" button
419      */
chooseBackground()420     public void chooseBackground()
421     {
422         try
423         {
424             setEnabled(btnBackgrounds, false);
425             if (bgDialog == null)
426             {
427                 bgDialog = new BackgroundsDialog(xMSF, settings.cp_BackgroundImages, resources);
428                 bgDialog.createWindowPeer(xControl.getPeer());
429             }
430             bgDialog.setSelected(settings.cp_DefaultSession.cp_Design.cp_BackgroundImage);
431             short i = bgDialog.executeDialog((UnoDialog) WWD_Events.this);
432             if (i == 1) //ok
433             {
434                 setBackground(bgDialog.getSelected());
435             }
436         }
437         catch (Exception ex)
438         {
439             ex.printStackTrace();
440         }
441         finally
442         {
443             setEnabled(btnBackgrounds, true);
444         }
445     }
446 
447     /**
448      * invoked when the BackgorundsDialog is "OKed".
449      */
setBackground(Object background)450     public void setBackground(Object background)
451     {
452         if (background == null)
453         {
454             background = PropertyNames.EMPTY_STRING;
455         }
456         settings.cp_DefaultSession.cp_Design.cp_BackgroundImage = (String) background;
457         refreshStylePreview();
458     }
459     private IconsDialog iconsDialog;
460 
461     /**
462      * is called when the user clicks "Icon sets" button.
463      *
464      */
chooseIconset()465     public void chooseIconset()
466     {
467         try
468         {
469             setEnabled(btnIconSets, false);
470             if (iconsDialog == null)
471             {
472                 iconsDialog = new IconsDialog(xMSF, settings.cp_IconSets, resources);
473                 iconsDialog.createWindowPeer(xControl.getPeer());
474             }
475 
476             iconsDialog.setIconset(settings.cp_DefaultSession.cp_Design.cp_IconSet);
477 
478             short i = iconsDialog.executeDialog((UnoDialog) WWD_Events.this);
479             if (i == 1) //ok
480             {
481                 setIconset(iconsDialog.getIconset());
482             }
483         }
484         catch (Exception ex)
485         {
486             ex.printStackTrace();
487         }
488         finally
489         {
490             setEnabled(btnIconSets, true);
491         }
492     }
493 
494     /**
495      * invoked when the Iconsets Dialog is OKed.
496      */
setIconset(String icon)497     public void setIconset(String icon)
498     {
499         settings.cp_DefaultSession.cp_Design.cp_IconSet = icon;
500         updateIconsetText();
501     }
502 
503     /* ******************************
504      * STEP 7
505      */
506     /**
507      * sets the publishing url of either a local/zip or ftp publisher.
508      * updates the ui....
509      */
setPublishUrl(String publisher, String url, int number)510     private CGPublish setPublishUrl(String publisher, String url, int number)
511     {
512         if (url == null)
513         {
514             return null;
515         }
516         CGPublish p = getPublisher(publisher);
517         p.cp_URL = url;
518         p.cp_Publish = true;
519         updatePublishUI(number);
520         p.overwriteApproved = true;
521         return p;
522     }
523 
524     /**
525      * updates the ui of a certain publisher
526      * (the text box url)
527      * @param number
528      */
updatePublishUI(int number)529     private void updatePublishUI(int number)
530     {
531         ((DataAware) pubAware.get(number)).updateUI();
532         ((DataAware) pubAware.get(number + 1)).updateUI();
533         checkPublish();
534     }
535 
536     /**
537      * The user clicks the local "..." button.
538      *
539      */
setPublishLocalDir()540     public void setPublishLocalDir()
541     {
542         String dir = showFolderDialog("Local destination directory", PropertyNames.EMPTY_STRING, settings.cp_DefaultSession.cp_OutDirectory);
543         //if ok was pressed...
544         setPublishUrl(LOCAL_PUBLISHER, dir, 0);
545 
546     }
547 
548     /**
549      * The user clicks the "Configure" FTP button.
550      *
551      */
setFTPPublish()552     public void setFTPPublish()
553     {
554         if (showFTPDialog(getPublisher(FTP_PUBLISHER)))
555         {
556             getPublisher(FTP_PUBLISHER).cp_Publish = true;
557             updatePublishUI(2);
558         }
559     }
560 
561     /**
562      * show the ftp dialog
563      * @param pub
564      * @return true if OK was pressed, otherwise false.
565      */
showFTPDialog(CGPublish pub)566     private boolean showFTPDialog(CGPublish pub)
567     {
568         try
569         {
570             return getFTPDialog(pub).execute(this) == 1;
571         }
572         catch (Exception ex)
573         {
574             ex.printStackTrace();
575             return false;
576         }
577     }
578 
579     /**
580      * the user clicks the zip "..." button.
581      * Choose a zip file...
582      */
setZipFilename()583     public void setZipFilename()
584     {
585         SystemDialog sd = getZipDialog();
586         String zipFile = sd.callStoreDialog(settings.cp_DefaultSession.cp_OutDirectory, resources.resDefaultArchiveFilename);
587         setPublishUrl(ZIP_PUBLISHER, zipFile, 4);
588         getPublisher(ZIP_PUBLISHER).overwriteApproved = true;
589     }
590     private TOCPreview docPreview;
591 
592     /**
593      * the user clicks the "Preview" button.
594      */
documentPreview()595     public void documentPreview()
596     {
597         try
598         {
599             if (docPreview == null)
600             {
601                 docPreview = new TOCPreview(xMSF, settings, resources, stylePreview.tempDir, myFrame);
602             }
603             docPreview.refresh(settings);
604         }
605         catch (Exception ex)
606         {
607             unexpectedError(ex);
608         }
609     }
610 
611     /* **********************
612      * FINISH
613      */
614     /**
615      * This method checks if the given target's path, added the pathExtension argument,
616      * exists, and asks the user what to do about it.
617      * If the user says its all fine, then the target will
618      * be replaced.
619      * @return true if "create" should continue. false if "create" should abort.
620      */
publishTargetApproved()621     private boolean publishTargetApproved()
622     {
623         boolean result = true;
624         // 1. check local publish target
625 
626         CGPublish p = getPublisher(LOCAL_PUBLISHER);
627 
628         // should publish ?
629         if (p.cp_Publish)
630         {
631             String path = getFileAccess().getPath(p.url, null);
632             // target exists?
633             if (getFileAccess().exists(p.url, false))
634             {
635                 //if its a directory
636                 if (getFileAccess().isDirectory(p.url))
637                 {
638                     //check if its empty
639                     String[] files = getFileAccess().listFiles(p.url, true);
640                     if (files.length > 0)
641                     {
642                         /* it is not empty :-(
643                          * it either a local publisher or an ftp (zip uses no directories
644                          * as target...)
645                          */
646                         String message = JavaTools.replaceSubString(resources.resLocalTragetNotEmpty,
647                                 path, "%FILENAME");
648                         result = AbstractErrorHandler.showMessage(
649                                 xMSF, xControl.getPeer(), message,
650                                 ErrorHandler.MESSAGE_WARNING, ErrorHandler.BUTTONS_YES_NO,
651                                 ErrorHandler.DEF_NO, ErrorHandler.RESULT_YES);
652 
653                         if (!result)
654                         {
655                             return result;
656                         }
657                     }
658                 }
659                 else
660                 {//not a directory, but still exists
661                     String message = JavaTools.replaceSubString(resources.resLocalTargetExistsAsfile,
662                             path, "%FILENAME");
663                     AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message, ErrorHandler.ERROR_PROCESS_FATAL);
664                     return false;
665                 }
666 
667             // try to write to the path...
668             }
669             else
670             {
671                 // the local target directory does not exist.
672                 String message = JavaTools.replaceSubString(resources.resLocalTargetCreate,
673                         path, "%FILENAME");
674                 try
675                 {
676                     result = AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
677                             ErrorHandler.ERROR_QUESTION_YES);
678                 }
679                 catch (Exception ex)
680                 {
681                     ex.printStackTrace();
682                 }
683 
684                 if (!result)
685                 {
686                     return result;
687                 // try to create the directory...
688                 }
689                 try
690                 {
691                     getFileAccess().fileAccess.createFolder(p.cp_URL);
692                 }
693                 catch (Exception ex)
694                 {
695                     message = JavaTools.replaceSubString(resources.resLocalTargetCouldNotCreate,
696                             path, "%FILENAME");
697                     AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
698                             ErrorHandler.ERROR_PROCESS_FATAL);
699                     return false;
700                 }
701             }
702         }
703 
704         // 2. Check ZIP
705         // should publish ?
706         p = getPublisher(ZIP_PUBLISHER);
707 
708         if (p.cp_Publish)
709         {
710 
711             String path = getFileAccess().getPath(p.cp_URL, null);
712             // target exists?
713             if (getFileAccess().exists(p.cp_URL, false))
714             {
715                 //if its a directory
716                 if (getFileAccess().isDirectory(p.cp_URL))
717                 {
718                     String message = JavaTools.replaceSubString(resources.resZipTargetIsDir,
719                             path, "%FILENAME");
720                     AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
721                             ErrorHandler.ERROR_PROCESS_FATAL);
722                     return false;
723                 }
724                 else
725                 {//not a directory, but still exists ( a file...)
726                     if (!p.overwriteApproved)
727                     {
728                         String message = JavaTools.replaceSubString(resources.resZipTargetExists,
729                                 path, "%FILENAME");
730                         result = AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
731                                 ErrorHandler.ERROR_QUESTION_YES);
732                         if (!result)
733                         {
734                             return false;
735                         }
736                     }
737                 }
738             }
739         }
740 
741         // 3. check FTP
742         p = getPublisher(FTP_PUBLISHER);
743 
744         // should publish ?
745         if (p.cp_Publish)
746         {
747 
748             String path = getFileAccess().getPath(p.cp_URL, null);
749 
750             // target exists?
751             if (getFileAccess().exists(p.url, false))
752             {
753                 //if its a directory
754                 if (getFileAccess().isDirectory(p.url))
755                 {
756                     //check if its empty
757                     String[] files = getFileAccess().listFiles(p.url, true);
758                     if (files.length > 0)
759                     {
760                         /* it is not empty :-(
761                          * it either a local publisher or an ftp (zip uses no directories
762                          * as target...)
763                          */
764                         String message = JavaTools.replaceSubString(resources.resFTPTargetNotEmpty,
765                                 path, "%FILENAME");
766                         result = AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
767                                 ErrorHandler.ERROR_QUESTION_CANCEL);
768                         if (!result)
769                         {
770                             return result;
771                         }
772                     }
773                 }
774                 else
775                 {//not a directory, but still exists (as a file)
776                     String message = JavaTools.replaceSubString(resources.resFTPTargetExistsAsfile,
777                             path, "%FILENAME");
778                     AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
779                             ErrorHandler.ERROR_PROCESS_FATAL);
780                     return false;
781                 }
782 
783             // try to write to the path...
784             }
785             else
786             {
787                 // the ftp target directory does not exist.
788                 String message = JavaTools.replaceSubString(resources.resFTPTargetCreate,
789                         path, "%FILENAME");
790                 result = AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
791                         ErrorHandler.ERROR_QUESTION_YES);
792                 if (!result)
793                 {
794                     return result;
795                 // try to create the directory...
796                 }
797                 try
798                 {
799                     getFileAccess().fileAccess.createFolder(p.url);
800                 }
801                 catch (Exception ex)
802                 {
803                     message = JavaTools.replaceSubString(resources.resFTPTargetCouldNotCreate,
804                             path, "%FILENAME");
805                     AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message,
806                             ErrorHandler.ERROR_PROCESS_FATAL);
807                     return false;
808                 }
809             }
810         }
811         return true;
812     }
813 
814     /*
815      * return false if "create" should be aborted. true if everything is fine.
816      */
saveSession()817     private boolean saveSession()
818     {
819         try
820         {
821             Object node = null;
822             String name = getSessionSaveName();
823 
824             //set documents index field.
825             ListModel docs = settings.cp_DefaultSession.cp_Content.cp_Documents;
826 
827             for (int i = 0; i < docs.getSize(); i++)
828             {
829                 ((CGDocument) docs.getElementAt(i)).cp_Index = i;
830             }
831             Object conf = Configuration.getConfigurationRoot(xMSF, CONFIG_PATH + "/SavedSessions", true);
832             // first I check if a session with the given name exists
833             try
834             {
835                 node = Configuration.getNode(name, conf);
836                 if (node != null)
837                 {
838                     if (!AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(),
839                             JavaTools.replaceSubString(resources.resSessionExists, name, "${NAME}"),
840                             ErrorHandler.ERROR_NORMAL_IGNORE))
841                     {
842                         return false;                    //remove the old session
843                     }
844                 }
845                 Configuration.removeNode(conf, name);
846 
847             }
848             catch (NoSuchElementException nsex)
849             {
850             }
851 
852             settings.cp_DefaultSession.cp_Index = 0;
853             node = Configuration.addConfigNode(conf, name);
854             settings.cp_DefaultSession.cp_Name = name;
855             settings.cp_DefaultSession.writeConfiguration(node, CONFIG_READ_PARAM);
856             settings.cp_SavedSessions.reindexSet(conf, name, "Index");
857             Configuration.commit(conf);
858 
859             // now I reload the sessions to actualize the list/combo boxes load/save sessions.
860             settings.cp_SavedSessions.clear();
861 
862             Object confView = Configuration.getConfigurationRoot(xMSF, CONFIG_PATH + "/SavedSessions", false);
863             settings.cp_SavedSessions.readConfiguration(confView, CONFIG_READ_PARAM);
864 
865             settings.cp_LastSavedSession = name;
866             currentSession = name;
867             // now save the name of the last saved session...
868 
869             settings.cp_LastSavedSession = name;
870 
871             // TODO add the <none> session...
872             prepareSessionLists();
873             ListModelBinder.fillList(lstLoadSettings, settings.cp_SavedSessions.items(), null);
874             ListModelBinder.fillComboBox(cbSaveSettings, settings.savedSessions.items(), null);
875             selectSession();
876 
877             currentSession = settings.cp_LastSavedSession;
878 
879             return true;
880         }
881         catch (Exception ex)
882         {
883             ex.printStackTrace();
884             return false;
885         }
886     }
887 
targetStringFor(String publisher)888     private String targetStringFor(String publisher)
889     {
890         CGPublish p = getPublisher(publisher);
891         if (p.cp_Publish)
892         {
893             return "\n" + getFileAccess().getPath(p.cp_URL, null);
894         }
895         else
896         {
897             return PropertyNames.EMPTY_STRING;
898         }
899     }
900 
901     /**
902      * this method will be called when the Status Dialog
903      * is hidden.
904      * It checks if the "Process" was successfull, and if so,
905      * it closes the wizard dialog.
906      */
finishWizardFinished()907     public void finishWizardFinished()
908     {
909         if (process.getResult())
910         {
911             String targets =
912                     targetStringFor(LOCAL_PUBLISHER) +
913                     targetStringFor(ZIP_PUBLISHER) +
914                     targetStringFor(FTP_PUBLISHER);
915             String message = JavaTools.replaceSubString(resources.resFinishedSuccess, targets, "%FILENAME");
916 
917             AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), message, ErrorHandler.ERROR_MESSAGE);
918             if (exitOnCreate)
919             {
920                 this.xDialog.endExecute();
921             }
922         }
923         else
924         {
925             AbstractErrorHandler.showMessage(xMSF, xControl.getPeer(), resources.resFinishedNoSuccess, ErrorHandler.ERROR_WARNING);
926         }
927     }
928 
cancel()929     public void cancel()
930     {
931         xDialog.endExecute();
932     }
933     private Process process;
934     private boolean exitOnCreate = true;
935 
936     /**
937      * the user clicks the finish/create button.
938      */
finishWizard()939     public boolean finishWizard()
940     {
941         finishWizard(true);
942         return true;
943     }
944 
945     /**
946      * finish the wizard
947      * @param exitOnCreate_ should the wizard close after
948      * a successfull create.
949      * Default is true,
950      * I have a hidden feature which enables false here
951      */
finishWizard(boolean exitOnCreate_)952     public void finishWizard(boolean exitOnCreate_)
953     {
954 
955         exitOnCreate = exitOnCreate_;
956 
957         /**
958          * First I check if ftp password was set, if not - the ftp dialog pops up...
959          * This may happen when a session is loaded, since the
960          * session saves the ftp url and username, but not the password.
961          */
962         final CGPublish p = getPublisher(FTP_PUBLISHER);
963         // if ftp is checked, and no proxies are set, and password is empty...
964         if (p.cp_Publish && (!proxies) && (p.password == null || p.password.equals(PropertyNames.EMPTY_STRING)))
965         {
966             if (showFTPDialog(p))
967             {
968                 updatePublishUI(2);
969                 //now continue...
970                 finishWizard2();
971             }
972         }
973         else
974         {
975             finishWizard2();
976         }
977     }
978 
979     /**
980      * this method is only called
981      * if ftp-password was eather set, or
982      * the user entered one in the FTP Dialog which
983      * popped up when clicking "Create".
984      *
985      */
finishWizard2()986     private void finishWizard2()
987     {
988 
989         CGPublish p = getPublisher(LOCAL_PUBLISHER);
990         p.url = p.cp_URL;
991 
992         /*
993          * zip publisher is using another url form...
994          */
995         p = getPublisher(ZIP_PUBLISHER);
996         //replace the '%' with '%25'
997         String url1 = JavaTools.replaceSubString(p.cp_URL, "%25", "%");
998         //replace all '/' with '%2F'
999         url1 = JavaTools.replaceSubString(url1, "%2F", "/");
1000 
1001         p.url = "vnd.sun.star.zip://" + url1 + "/";
1002 
1003         /*
1004          * and now ftp...
1005          */
1006         p = getPublisher(FTP_PUBLISHER);
1007         p.url = FTPDialog.getFullURL(p);
1008 
1009 
1010         /* first we check the publishing targets. If they exist we warn and ask
1011          * what to do. a False here means the user said "cancel" (or rather: clicked...)
1012          */
1013         if (!publishTargetApproved())
1014         {
1015             return;
1016         /*
1017          * In order to save the session correctly,
1018          * I return the value of the ftp publisher cp_Publish
1019          * property to its original value...
1020          */
1021         }
1022         p.cp_Publish = __ftp;
1023 
1024         //if the "save settings" checkbox is on...
1025         if (isSaveSession())
1026         {
1027             // if canceled by user
1028             if (!saveSession())
1029             {
1030                 return;
1031             }
1032         }
1033         else
1034         {
1035             settings.cp_LastSavedSession = PropertyNames.EMPTY_STRING;
1036         }
1037         try
1038         {
1039             Object conf = Configuration.getConfigurationRoot(xMSF, CONFIG_PATH, true);
1040             Configuration.set(
1041                     settings.cp_LastSavedSession,
1042                     "LastSavedSession", conf);
1043             Configuration.commit(conf);
1044         }
1045         catch (Exception ex)
1046         {
1047             ex.printStackTrace();
1048         }
1049 
1050         /*
1051          * again, if proxies are on, I disable ftp before the creation process
1052          * starts.
1053          */
1054         if (proxies)
1055         {
1056             p.cp_Publish = false;
1057 
1058         /*
1059          * There is currently a bug, which crashes office when
1060          * writing folders to an existing zip file, after deleting
1061          * its content, so I "manually" delete it here...
1062          */
1063         }
1064         p = getPublisher(ZIP_PUBLISHER);
1065         if (getFileAccess().exists(p.cp_URL, false))
1066         {
1067             getFileAccess().delete(p.cp_URL);
1068         }
1069         try
1070         {
1071 
1072             ErrorHandler eh = new ProcessErrorHandler(xMSF, xControl.getPeer(), resources);
1073 
1074             process = new Process(settings, xMSF, eh);
1075 
1076             StatusDialog pd = getStatusDialog();
1077 
1078             pd.setRenderer(new ProcessStatusRenderer(resources));
1079             pd.execute(this, process.myTask, resources.prodName);  //process,
1080             process.runProcess();
1081             finishWizardFinished();
1082             process.myTask.removeTaskListener(pd);
1083 
1084         }
1085         catch (Exception ex)
1086         {
1087             ex.printStackTrace();
1088         }
1089 
1090     }
1091 
1092     /**
1093      * implements a hidden feature for "finishing" without
1094      * closing the wizard.
1095      * press "&%" quite fast when the focus is on one
1096      * of the last steps' checkboxes.
1097      * @author rp143992
1098      */
1099     private class Create implements XKeyListener
1100     {
1101 
1102         long time = 0;
1103         int count = 0;
1104 
1105         /* (non-Javadoc)
1106          * @see com.sun.star.awt.XKeyListener#keyPressed(com.sun.star.awt.KeyEvent)
1107          */
keyPressed(KeyEvent ke)1108         public void keyPressed(KeyEvent ke)
1109         {
1110             if (ke.KeyChar == '&')
1111             {
1112                 time = System.currentTimeMillis();
1113             }
1114             else if (ke.KeyChar == '%' && ((System.currentTimeMillis() - time) < 300))
1115             {
1116                 Boolean b = (Boolean) getControlProperty("btnWizardFinish", PropertyNames.PROPERTY_ENABLED);
1117                 if (b.booleanValue())
1118                 {
1119                     finishWizard(false);
1120                 }
1121             }
1122         }
1123 
keyReleased(KeyEvent arg0)1124         public void keyReleased(KeyEvent arg0)
1125         {
1126         }
1127 
disposing(EventObject arg0)1128         public void disposing(EventObject arg0)
1129         {
1130         }
1131     }
1132 
1133     /**
1134      * is called on the WindowHidden event,
1135      * deletes the temporary directory.
1136      */
cleanup()1137     public void cleanup()
1138     {
1139 
1140 
1141         try
1142         {
1143             dpStylePreview.dispose();
1144         }
1145         catch (Exception ex)
1146         {
1147             ex.printStackTrace();
1148         }
1149 
1150         stylePreview.cleanup();
1151 
1152         try
1153         {
1154             if (bgDialog != null)
1155             {
1156                 bgDialog.xComponent.dispose();
1157             }
1158         }
1159         catch (Exception ex)
1160         {
1161             ex.printStackTrace();
1162         }
1163 
1164         try
1165         {
1166             if (iconsDialog != null)
1167             {
1168                 iconsDialog.xComponent.dispose();
1169             }
1170         }
1171         catch (Exception ex)
1172         {
1173             ex.printStackTrace();
1174         }
1175 
1176         try
1177         {
1178             if (ftpDialog != null)
1179             {
1180                 ftpDialog.xComponent.dispose();
1181             }
1182         }
1183         catch (Exception ex)
1184         {
1185             ex.printStackTrace();
1186         }
1187 
1188         try
1189         {
1190             xComponent.dispose();
1191         }
1192         catch (Exception ex)
1193         {
1194             ex.printStackTrace();
1195         }
1196 
1197         try
1198         {
1199             //XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, myDocument);
1200             //if (xCloseable != null)
1201             //    xCloseable.close(false);
1202 
1203             XCloseable xCloseable = UnoRuntime.queryInterface(XCloseable.class, myFrame);
1204             if (xCloseable != null)
1205             {
1206                 xCloseable.close(false);
1207             }
1208         }
1209         catch (Exception ex)
1210         {
1211             ex.printStackTrace();
1212         }
1213 
1214     }
1215 
1216     public class LoadDocs
1217     {
1218 
1219         private XControl xC;
1220         String[] files;
1221         Task task;
1222 
LoadDocs(XControl xC_, String[] files_, Task task_)1223         public LoadDocs(XControl xC_, String[] files_, Task task_)
1224         {
1225             xC = xC_;
1226             files = files_;
1227             task = task_;
1228         }
1229 
loadDocuments()1230         public void loadDocuments()
1231         {
1232             //LogTaskListener lts = new LogTaskListener();
1233             //task.addTaskListener(lts);
1234 
1235 //            task.start();
1236 
1237             // where the documents are added to in the list (offset)
1238             int offset = (getSelectedDoc().length > 0 ? selectedDoc[0] + 1 : getDocsCount());
1239 
1240             /* if the user chose one file, the list starts at 0,
1241              * if he chose more than one, the first entry is a directory name,
1242              * all the others are filenames.
1243              */
1244             int start = (files.length > 1 ? 1 : 0);
1245             /*
1246              * Number of documents failed to validate.
1247              */
1248             int failed = 0;
1249 
1250             // store the directory
1251             settings.cp_DefaultSession.cp_InDirectory = start == 1 ? files[0] : FileAccess.getParentDir(files[0]);
1252 
1253             /*
1254              * Here i go through each file, and validate it.
1255              * If its ok, I add it to the ListModel/ConfigSet
1256              */
1257             for (int i = start; i < files.length; i++)
1258             {
1259                 CGDocument doc = new CGDocument();
1260                 doc.setRoot(settings);
1261 
1262                 doc.cp_URL = (start == 0) ? files[i] : FileAccess.connectURLs(files[0], files[i]);
1263 
1264                 /* so - i check each document and if it is ok I add it.
1265                  * The failed variable is used only to calculate the place to add -
1266                  * Error reporting to the user is (or should (-:  )done in the checkDocument(...) method
1267                  */
1268                 if (checkDocument(doc, task, xC))
1269                 {
1270                     settings.cp_DefaultSession.cp_Content.cp_Documents.add(offset + i - failed - start, doc);
1271                 }
1272                 else
1273                 {
1274                     failed++;
1275                 }
1276             }
1277 
1278             // if any documents where added,
1279             // set the first one to be the current-selected document.
1280             if (files.length > start + failed)
1281             {
1282                 setSelectedDoc(new short[]
1283                         {
1284                             (short) offset
1285                         });
1286             }
1287             // update the ui...
1288             docListDA.updateUI();
1289             // this enables/disables the next steps.
1290             // when no documents in the list, all next steps are disabled
1291             checkSteps();
1292             /* a small insurance that the status dialog will
1293              * really close...
1294              */
1295             while (task.getStatus() < task.getMax())
1296             {
1297                 task.advance(false);
1298             }
1299         }
1300     }
1301 }
1302 
1303