1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 *
23 *
24 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
25 * Use is subject to license terms.
26 *
27 * pmTop.java
28 * Top level
29 */
30
31package com.sun.admin.pm.client;
32
33import java.awt.*;
34import java.awt.event.*;
35import java.util.*;
36import java.util.Vector;
37import java.lang.*;
38import javax.swing.JPanel;
39import javax.swing.JTable;
40import javax.swing.ListSelectionModel;
41import javax.swing.event.ListSelectionListener;
42import javax.swing.event.ListSelectionEvent;
43import javax.swing.table.AbstractTableModel;
44import javax.swing.text.*;
45import javax.swing.border.*;
46import javax.swing.*;
47
48import com.sun.admin.pm.server.*;
49
50
51/*
52 * Top window for printer manager
53 */
54
55public class pmTop extends JPanel {
56
57    static private pmTop myTop = null;
58    static private pmHelpFrame helpFrame = null;
59    static private pmAboutBox aboutBox = null;
60    static private pmLogDisplay commandLog = null;
61    static private pmFindFrame findFrame = null;
62
63    JLabel nameserviceLabel = new JLabel();
64    JLabel domainhostLabel;
65    JLabel defaultpLabel;
66    String defaultPrinter;
67    JScrollPane scrollPane;
68    JTable listTable;
69    Host host = new Host();
70    private JPanel north = new JPanel();
71    JPanel center;
72    listTableModel listModel;
73    ListSelectionModel listSM;
74
75    JMenuBar menuBar;
76    JFrame parentFrame;
77    JCheckBoxMenuItem logCheck;
78    JCheckBoxMenuItem confirmCheck;
79    JCheckBoxMenuItem usePPD;
80    JCheckBoxMenuItem useLocalhost;
81    JMenuItem modifyMenuItem = null;
82    JMenuItem deleteMenuItem = null;
83
84    JMenuItem access;
85    JMenuItem local;
86    JMenuItem network;
87
88    int actionindex = 0;
89    private String newNS;
90    NameService ns = null;
91    NameService nisns = null;
92    NameService systemns = null;
93    NameService ldapns = null;
94
95    pmAccess accessView = null;
96    pmInstallPrinter localinstallView = null;
97    pmInstallPrinter networkinstallView = null;
98    pmDelete deleteView = null;
99    pmInstallPrinter modifyView = null;
100    pmLoad loadView = null;
101
102    String clickedPrinter;
103    String selectedPrinter = null;
104    String selprinterServer = null;
105    int selectedRow = -1;
106
107    String cmdLog = null;
108    String errorLog = null;
109    String warningLog = null;
110
111    boolean runningAuth = false;
112    boolean isRoot = false;
113
114    pmFrame frame;
115
116
117    public pmTop(JFrame parent) {
118	parentFrame = parent;
119	setLayout(new BorderLayout());
120	pmTopInit();
121
122    }
123
124    public void pmTopInit() {
125
126	try {
127		systemns = new NameService("system");
128	} catch (Exception e) {
129		Debug.message("CLNT:  system:Nameservice exception " + e);
130	}
131	try {
132		nisns = new NameService("nis");
133	} catch (Exception e) {
134		Debug.message("CLNT:  nis:Nameservice exception " + e);
135	}
136	try {
137		ldapns = new NameService("ldap");
138	} catch (Exception e) {
139		Debug.message("CLNT:  ldap:Nameservice exception " + e);
140	}
141
142	ns = systemns;
143	newNS = "files";
144
145        // determine root privileges
146        try {
147            ns.checkAuth();
148        } catch (Exception ax) {
149            Debug.message("CLNT:  checkAuth threw " + ax);
150        }
151
152        if (ns.isAuth()) {
153	    runningAuth = true;
154	    isRoot = true;
155            Debug.message("CLNT:  Running as root");
156        } else
157            Debug.message("CLNT:  Not running as root");
158
159	northPanel();
160	centerPanel();
161	southPanel();
162
163    }
164
165    // Set values so that printer selection null
166    public void clearSelected() {
167	selectedPrinter = null;
168	selprinterServer = null;
169	selectedRow = -1;
170    	enableEditMenuItems(false);
171    }
172
173
174    // Create north panel with GridBagLayout
175    public void northPanel() {
176
177	menuBar = new JMenuBar();
178	menuBar.setBorder(new EmptyBorder(5, 5, 5, 5));
179	menuBar.add(appMenu());
180	menuBar.add(objectMenu());
181	menuBar.add(toolsMenu());
182	menuBar.add(Box.createHorizontalGlue());
183	menuBar.add(helpMenu());
184
185	parentFrame.setJMenuBar(menuBar);
186    }
187
188    public class listTableModel extends AbstractTableModel {
189	int numColumns;
190
191        String[] columnNames = {
192            pmUtility.getResource("Printer.Name"),
193            pmUtility.getResource("Printer.Server"),
194            pmUtility.getResource("Description")
195
196        };
197
198	// Initialize for JTable calls from SWING classes
199	Vector data = new Vector(0, 0);
200
201        public listTableModel() {
202            numColumns = getColumnCount();
203        }
204
205	public void insertlistTable(String rowDataList[], int numcols) {
206		Vector rowData = new Vector(3, 1);
207		data = new Vector(100, 5);
208		int j = 0;
209
210		if ((rowDataList.length) <= 1) {
211			return;
212		}
213
214		for (int i = 0; i < rowDataList.length; i = i + 3) {
215			rowData = new Vector(3, 1);
216			for (j = 0; j < 3; j++) {
217			    rowData.addElement(
218				rowDataList[i + j]);
219			}
220			data.addElement(rowData);
221		}
222	}
223
224	public void removeRow(int row) {
225		data.removeElementAt(row);
226	}
227
228	public int getRowCount() {
229		return data.size();
230	}
231
232	public int getColumnCount() {
233		return columnNames.length;
234	}
235
236	public String getColumnName(int col) {
237		return columnNames[col];
238	}
239
240	public Object getValueAt(int row, int col) {
241		Vector rowVector = (Vector)data.elementAt(row);
242		return rowVector.elementAt(col);
243	}
244
245	public void setValueAt(String value, int row, int col) {
246		Vector rowVector = (Vector)data.elementAt(row);
247		rowVector.setElementAt(value, col);
248	}
249
250	public void addRow(Vector row) {
251		data.addElement(row);
252	}
253
254	public int findValue(String value) {
255		for (int i = 0; i < data.size(); i++) {
256			if (getValueAt(i, 0).equals(value))
257				return i;
258		}
259		return -1;
260	}
261
262    };
263
264
265    // called on enter or double-click
266    void modifySelectedPrinter() {
267
268        ListSelectionModel m = listTable.getSelectionModel();
269
270        if (m.isSelectionEmpty()) {
271            Debug.message("CLNT:  list selection is empty");
272            return;
273        }
274
275        int selectedRow = m.getMinSelectionIndex();
276
277        Debug.message("CLNT:  list row selected is " + selectedRow);
278
279        selectedPrinter =
280            (String) listTable.getModel().getValueAt(selectedRow, 0);
281        selprinterServer =
282                    (String)listTable.getModel().getValueAt(selectedRow, 1);
283
284        Debug.message("CLNT:  selectedPrinter is " + selectedPrinter);
285
286        doModify();
287    }
288
289
290    // Create printer list in center panel
291    public void centerPanel() {
292
293	center = new JPanel();
294
295	listModel = new listTableModel();
296	listTable = new JTable(listModel);
297        listTable.setColumnSelectionAllowed(false);
298        listTable.setRowSelectionAllowed(true);
299	listTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
300        listTable.setShowGrid(false);
301        listTable.registerKeyboardAction(new ActionListener() {
302
303	public void actionPerformed(ActionEvent e) {
304            Debug.message("CLNT:  enter action");
305            if (runningAuth)
306                modifySelectedPrinter();
307            else
308               Toolkit.getDefaultToolkit().beep();
309            }},
310            KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
311            JComponent.WHEN_IN_FOCUSED_WINDOW);
312
313
314	listTable.addMouseListener(new MouseAdapter() {
315	    public void mouseClicked(MouseEvent e) {
316                Point pt = e.getPoint();
317                int rowIndex = listTable.rowAtPoint(pt);
318                int colIndex = listTable.columnAtPoint(pt);
319                int clickCount = e.getClickCount();
320
321                Debug.message("CLNT:  getClickCount() is " + clickCount);
322
323                if (clickCount == 2) {
324                    if (rowIndex == -1) {
325                        Debug.message("CLNT:  clicked outside table");
326                    } else {
327                        if (runningAuth)
328                            modifySelectedPrinter();
329                        else
330                            Toolkit.getDefaultToolkit().beep();
331                    }
332                }
333            }
334	});
335
336	// Add selection listener
337	ListSelectionModel rowSelectModel = listTable.getSelectionModel();
338
339	rowSelectModel.addListSelectionListener(new ListSelectionListener() {
340
341	    public void valueChanged(ListSelectionEvent e) {
342
343		listSM = (ListSelectionModel)e.getSource();
344		Debug.message("CLNT:  listSM is " + listSM);
345
346		if (listSM.isSelectionEmpty()) {
347                           Debug.message("CLNT:  list selection is empty");
348                           enableEditMenuItems(false);
349		} else {
350		    selectedRow = listSM.getMinSelectionIndex();
351		    Debug.message(
352			"CLNT:  list element selected" + selectedRow);
353		    selectedPrinter =
354		    (String)listTable.getModel().getValueAt(selectedRow, 0);
355		    selprinterServer =
356			(String)listTable.getModel().getValueAt(selectedRow, 1);
357		    Debug.message(
358			"CLNT:  selectedPrinter is " + selectedPrinter);
359		    enableEditMenuItems(true);
360		}
361	    }
362	});
363
364	GridBagConstraints c = new GridBagConstraints();
365	center.setLayout(new BorderLayout());
366
367	c.insets = new Insets(35, 50, 35, 50);
368
369	try {
370            listModel.insertlistTable(PrinterUtil.getPrinterList(ns),
371			listModel.getColumnCount());
372	} catch (Exception e) {
373		Debug.fatal("CLNT:  pmTop:getPrinterList() caught " + e);
374		pmMessageDialog m = new pmMessageDialog(
375		frame,
376		    pmUtility.getResource("Error"),
377		    pmUtility.getResource(
378			"Cannot.get.list.of.printers.Exiting."),
379		    myTop,
380		    "getPrinterListFailed");
381		m.setVisible(true);
382		System.exit(-1);
383	}
384
385	scrollPane = new JScrollPane();
386	scrollPane.setViewportView(listTable);
387
388	listTable.setPreferredScrollableViewportSize(
389					new Dimension(500, 500));
390	scrollPane.getViewport().setView(listTable);
391	center.add(scrollPane);
392	add("Center", center);
393    }
394
395	// Create south panel with grid layout
396
397    public void southPanel() {
398	JPanel south = new JPanel();
399	GridBagConstraints c = new GridBagConstraints();
400	south.setLayout(new GridBagLayout());
401
402	// Constraints applied across all entries
403	c.fill = GridBagConstraints.BOTH;
404	c.insets = new Insets(6, 6, 6, 6);
405	c.gridheight = 1;
406	c.gridwidth = 1;
407	c.gridy = 1;
408
409	// Create the labels
410	c.gridx = 0;
411	c.weightx = c.weighty = 1.0;
412
413	try {
414	defaultpLabel =
415		new JLabel(pmUtility.getResource("Default.Printer:") +
416                       " " + PrinterUtil.getDefaultPrinter(ns));
417
418	} catch (Exception e) {
419		Debug.warning("CLNT:  pmTop:getDefaultPrinter() caught " + e);
420		defaultpLabel =	new JLabel(
421			pmUtility.getResource("Default.Printer:"));
422	}
423
424	south.add(defaultpLabel, c);
425
426
427	if (newNS.startsWith("files")) {
428		try {
429			domainhostLabel = new JLabel(pmUtility.getResource(
430				"Host:") + " " + host.getLocalHostName());
431
432			nameserviceLabel.setText("    ");
433
434		} catch (Exception e) {
435		    Debug.warning("CLNT: pmTop:getLocalHostName caught " + e);
436		}
437
438	} else {
439		try {
440		    nameserviceLabel.setText(
441		    pmUtility.getResource("Naming.Service:") + " " + newNS);
442		   domainhostLabel = new JLabel(
443			pmUtility.getResource("Domain:") + " " +
444                   host.getDomainName());
445		} catch (Exception e) {
446		    Debug.warning("CLNT: pmTop:getDomainName caught " + e);
447		}
448	}
449
450	c.weightx = c.weighty = 1.0;
451	c.gridx = 2;
452	south.add(nameserviceLabel, c);
453	c.gridx = 3;
454	south.add(domainhostLabel, c);
455	add("South", south);
456    }
457
458
459	public JMenu appMenu() {
460        // name service
461        // ---
462        // cmd line console
463        // confirm all actions
464	// use ppd file
465        // ---
466        // exit
467
468        JMenu appMenu = new JMenu(pmUtility.getResource("Print.Manager"));
469        appMenu.setMnemonic(
470            pmUtility.getIntResource("Print.Manager.mnemonic"));
471
472	appMenu.addMouseListener(new MouseAdapter() {
473		public void mouseClicked(MouseEvent e) {
474			Debug.message("CLNT: appMenu MouseListener");
475		};
476	});
477
478        JMenuItem load = new JMenuItem(
479            pmUtility.getResource("Select.Naming.Service"),
480            pmUtility.getIntResource("Select.Naming.Service.mnemonic"));
481
482        load.addActionListener(
483            new ActionListener() {
484            public void actionPerformed(ActionEvent e) {
485			    Debug.message("CLNT:  call from load action");
486                if (loadView != null)
487                    loadView.setVisible(true);
488                else
489                    loadView = new pmLoad(myTop);
490                loadView.Show();
491
492            };
493        });
494        load.setEnabled(true);
495        appMenu.add(load);
496
497        appMenu.addSeparator();
498
499		logCheck = new JCheckBoxMenuItem(
500            pmUtility.getResource("Show.Command-Line.Console"));
501		logCheck.setMnemonic(
502            pmUtility.getIntResource("Show.Command-Line.Console.mnemonic"));
503
504        logCheck.addActionListener(new AbstractAction() {
505            public void actionPerformed(ActionEvent e) {
506			    Debug.message("CLNT:  call from checkbox action");
507                JCheckBoxMenuItem c = (JCheckBoxMenuItem) e.getSource();
508                if (c.isSelected() == true) {
509                    commandLog.setVisible(true);
510                } else {
511                    commandLog.setVisible(false);
512                }
513            }
514        });
515
516        if (!runningAuth)
517            logCheck.setEnabled(false);
518
519	appMenu.add(logCheck);
520
521        confirmCheck = new JCheckBoxMenuItem(
522            pmUtility.getResource("Confirm.All.Actions"), false);
523		confirmCheck.setMnemonic(
524		    pmUtility.getIntResource("Confirm.All.Actions.mnemonic"));
525        if (!runningAuth)
526            confirmCheck.setEnabled(false);
527
528	appMenu.add(confirmCheck);
529
530	usePPD = new JCheckBoxMenuItem(
531		pmUtility.getResource("Use.PPD.files"), true);
532	usePPD.setMnemonic(pmUtility.getIntResource("Use.PPD.files.mnemonic"));
533
534	useLocalhost = new JCheckBoxMenuItem(
535		pmUtility.getResource("Use.localhost"), false);
536	useLocalhost.setMnemonic(
537		pmUtility.getIntResource("Use.localhost.mnemonic"));
538
539
540	if (!runningAuth) {
541		usePPD.setEnabled(false);
542		useLocalhost.setEnabled(false);
543	}
544	appMenu.add(usePPD);
545	appMenu.add(useLocalhost);
546
547        appMenu.addSeparator();
548
549        JMenuItem exit = new JMenuItem(
550            pmUtility.getResource("Exit"),
551            pmUtility.getIntResource("Exit.mnemonic"));
552
553        exit.addActionListener(
554            new ActionListener() {
555            public void actionPerformed(ActionEvent e) {
556                Debug.message("CLNT:  call from exit action");
557                System.exit(0);
558            };
559        });
560
561        exit.setEnabled(true);
562        appMenu.add(exit);
563
564        return appMenu;
565    }
566
567    // disable everything is not running as root
568	public JMenu objectMenu() {
569        // add access to printer...
570        // ---
571        // new local printer...
572        // new network printer...
573        // ---
574        // delete printer
575        // modify properties...
576
577        JMenu objectMenu = new JMenu(
578            pmUtility.getResource("Printer"));
579
580        objectMenu.setMnemonic(
581            pmUtility.getIntResource("Printer.mnemonic"));
582
583            access = new JMenuItem(
584            pmUtility.getResource("Add.Access.to.Printer..."),
585            pmUtility.getIntResource("Add.Access.to.Printer.mnemonic"));
586
587        access.addActionListener(
588	    new ActionListener() {
589		public void actionPerformed(ActionEvent e) {
590                	Debug.message("CLNT:  call from access action");
591			if (accessView != null)
592                		accessView.setVisible(true);
593			else
594                   		accessView = new pmAccess(myTop);
595		    accessView.Show();
596		};
597	    });
598
599        if (!runningAuth)
600            access.setEnabled(false);
601
602        objectMenu.add(access);
603        objectMenu.addSeparator();
604
605        local = new JMenuItem(
606            pmUtility.getResource("New.Attached.Printer..."),
607            pmUtility.getIntResource("New.Attached.Printer.mnemonic"));
608
609        local.addActionListener(
610            new ActionListener() {
611            public void actionPerformed(ActionEvent e) {
612                Debug.message("CLNT:  call from localinstall action");
613                if (localinstallView != null)
614                    localinstallView.setVisible(true);
615		else {
616		    try {
617                	localinstallView = new pmInstallPrinter(
618					myTop, Constants.ADDLOCAL);
619		    } catch (Exception ex) {
620			Debug.message("CLNT:pmTop:caught exception"  + ex);
621		    }
622		}
623                localinstallView.Show();
624            };
625        });
626
627        if (!runningAuth)
628            local.setEnabled(false);
629
630        objectMenu.add(local);
631
632        network = new JMenuItem(
633            pmUtility.getResource("New.Network.Printer..."),
634            pmUtility.getIntResource("New.Network.Printer.mnemonic"));
635
636        network.addActionListener(
637            new ActionListener() {
638            public void actionPerformed(ActionEvent e) {
639                Debug.message("CLNT:  call from networkinstall action");
640                if (networkinstallView != null)
641                    networkinstallView.setVisible(true);
642		else {
643		    try {
644                    networkinstallView = new
645                        pmInstallPrinter(myTop, Constants.ADDNETWORK);
646		    } catch (Exception ex) {
647			Debug.message("CLNT:pmTop:caught exception" + ex);
648		    }
649		}
650
651                networkinstallView.Show();
652            };
653        });
654
655        if (!runningAuth)
656            network.setEnabled(false);
657
658        objectMenu.add(network);
659        objectMenu.addSeparator();
660
661        modifyMenuItem = new JMenuItem(
662            pmUtility.getResource("Modify.Printer.Properties..."),
663            pmUtility.getIntResource("Modify.Printer.Properties.mnemonic"));
664
665	    modifyMenuItem.addActionListener(
666            new ActionListener() {
667            public void actionPerformed(ActionEvent e) {
668
669		Debug.message("CLNT:  Modify " + selectedPrinter);
670		Debug.message("CLNT:  Modify " + selprinterServer);
671
672		doModify();
673            };
674        });
675
676        modifyMenuItem.setEnabled(false);
677        objectMenu.add(modifyMenuItem);
678
679        deleteMenuItem = new JMenuItem(
680            pmUtility.getResource("Delete.Printer..."),
681            pmUtility.getIntResource("Delete.Printer.mnemonic"));
682
683        deleteMenuItem.addActionListener(
684            new ActionListener() {
685		public void actionPerformed(ActionEvent e) {
686		    Debug.message("CLNT:  call from delete action");
687			if (selectedPrinter == null) {
688			    Debug.warning("CLNT:  selectedPrinter is null");
689			    Debug.message("CLNT:  cannot call pmDelete");
690			    // show error window
691			} else {
692			    deleteView = new pmDelete(myTop);
693			}
694            };
695        });
696        deleteMenuItem.setEnabled(false);
697        objectMenu.add(deleteMenuItem);
698        return objectMenu;
699    }
700
701    // returns true iff name was found in the printer list
702    public boolean findPrinterInList(String name) {
703
704        int row = -1;
705
706        try {
707            String p = name.trim();
708            row = listModel.findValue(p);
709        } catch (Exception ee) {
710            Debug.warning("CLNT:  pmTop:find ActionList: caught " + ee);
711        }
712
713        if (row != -1) {
714            selectedRow = row;
715            listTable.clearSelection();
716            listTable.setRowSelectionInterval(row, row);
717            listTable.scrollRectToVisible(listTable.getCellRect(row, 0, true));
718            listTable.revalidate();
719            scrollPane.revalidate();
720            scrollPane.repaint();
721        }
722        return row != -1;
723    }
724
725    public JMenu toolsMenu() {
726
727        // find printer...
728        JMenu toolsMenu = new JMenu(
729            pmUtility.getResource("Tools"));
730        toolsMenu.setMnemonic(
731            pmUtility.getIntResource("Tools.mnemonic"));
732
733        JMenuItem find = new JMenuItem(
734            pmUtility.getResource("Find.Printer"),
735            pmUtility.getIntResource("Find.Printer.mnemonic"));
736        find.addActionListener(
737            new ActionListener() {
738            public void actionPerformed(ActionEvent e) {
739                Debug.message("CLNT:  call from find action");
740                findFrame.setVisible(true);
741            }
742        });
743
744        toolsMenu.add(find);
745        return toolsMenu;
746    }
747
748	// Create help Menu
749
750    public JMenu helpMenu() {
751        JMenu helpMenu = new JMenu(pmUtility.getResource("Help"));
752		helpMenu.setMnemonic(pmUtility.getIntResource("Help.mnemonic"));
753
754        JMenuItem ov = new JMenuItem(
755            pmUtility.getResource("Overview"),
756            pmUtility.getIntResource("Overview.mnemonic"));
757        ov.addActionListener(new ActionListener() {
758            public void actionPerformed(ActionEvent e) {
759              myTop.showHelpItem("Overview");
760            };
761        });
762
763        helpMenu.add(ov);
764
765        JMenuItem on = new JMenuItem(
766            pmUtility.getResource("On.Help"),
767            pmUtility.getIntResource("On.Help.mnemonic"));
768        on.addActionListener(new ActionListener() {
769            public void actionPerformed(ActionEvent e) {
770              myTop.showHelpItem("HelpOnHelp");
771            };
772        });
773
774        helpMenu.add(on);
775        helpMenu.addSeparator();
776
777        JMenuItem about = new JMenuItem(
778            pmUtility.getResource("About.Print.Manager"),
779            pmUtility.getIntResource("About.Print.Manager.mnemonic"));
780        about.addActionListener(new ActionListener() {
781            public void actionPerformed(ActionEvent e) {
782		Debug.message("CLNT:  call from about help action");
783		aboutBox.setVisible(true);
784            };
785        });
786
787        helpMenu.add(about);
788        helpMenu.addSeparator();
789
790        JMenuItem settings = new JMenuItem(
791            pmUtility.getResource("Print.Manager.Settings"),
792            pmUtility.getIntResource("Print.Manager.Settings.mnemonic"));
793	    settings.addActionListener(new ActionListener() {
794		public void actionPerformed(ActionEvent e) {
795		    Debug.message("CLNT:  print manager settings help action");
796		    myTop.showHelpItem("PrintManagerSettings");
797		};
798        });
799
800        helpMenu.add(settings);
801        return helpMenu;
802    }
803
804    public void actionPerformed(java.awt.event.ActionEvent e) {
805    }
806
807    public void doModify() {
808
809        if (modifyView != null)
810            modifyView.pmScreendispose();
811
812	    try {
813
814		if (selectedPrinter == null || selprinterServer == null) {
815
816		} else {
817
818		    if ((host.getLocalHostName()).equals(selprinterServer) ||
819			selprinterServer.equals("localhost")) {
820
821			if (isNetwork()) {
822
823			    modifyView = new
824				pmInstallPrinter(
825					myTop, Constants.MODIFYNETWORK);
826
827			} else {
828			    modifyView = new
829				pmInstallPrinter(
830					myTop, Constants.MODIFYATTACHED);
831			}
832
833			modifyView.Show();
834
835		    } else {
836
837			try {
838				modifyView = new pmInstallPrinter(
839					myTop, Constants.MODIFYREMOTE);
840			} catch (Exception e) {
841				Debug.message(
842				"CLNT:pmTop:caught exception" + e);
843			}
844			modifyView.Show();
845		    }
846		}
847	    } catch (Exception e) {
848		Debug.warning("CLNT:  pmTop:getLocalHostName() caught " + e);
849        }
850    } // doModify()
851
852
853    public boolean isNetwork() {
854
855	Printer newpr = new Printer(myTop.ns);
856	newpr.setPrinterName(selectedPrinter);
857
858	try {
859		newpr.getPrinterDetails();
860	} catch (Exception e) {
861		Debug.warning("CLNT:  pmTop:getPrinterDetails() caught " + e);
862	}
863
864	pmCalls.debugShowPrinter(newpr);
865
866	if (newpr.getDestination() != null)  {
867		Debug.message("CLNT:  isNetwork:getDestination " +
868                          newpr.getDestination());
869		return true;
870	} else {
871		Debug.message("CLNT:  isNetwork:getDestination is null");
872		return false;
873	}
874    }
875
876    // Set the new namespace
877    public void pmsetNS() {
878
879	String serverNS;
880
881	// translate from gui to server
882	if (newNS.startsWith("files")) {
883		serverNS = new String("system");
884		useLocalhost.setState(true);
885	} else if (newNS.equals("NIS")) {
886		serverNS = new String("nis");
887		useLocalhost.setState(false);
888	} else if (newNS.equals("LDAP")) {
889		serverNS = new String("ldap");
890		useLocalhost.setState(false);
891	} else {
892		serverNS = new String("system");
893		useLocalhost.setState(true);
894	}
895
896        Debug.message("CLNT:  newNS: " + newNS +
897                       "\n serverNS: " + serverNS +
898                       "\n ns.getNameService(): " + ns.getNameService());
899
900	if (!serverNS.equals(ns.getNameService())) {
901
902		if (newNS.startsWith("files")) {
903			useLocalhost.setState(true);
904			ns = systemns;
905		} else if (newNS.equals("NIS")) {
906			useLocalhost.setState(false);
907			ns = nisns;
908		} else if (newNS.equals("LDAP")) {
909			useLocalhost.setState(false);
910			ns = ldapns;
911		} else {
912			useLocalhost.setState(true);
913			ns = systemns;
914		}
915	}
916
917
918	// This tool is read-only unless the user is root on the
919	// print server. Thus, don't check for namespace authorization
920	// if user is not root.
921
922	if (isRoot) {
923		// Check if user is authorized with this nameservice
924		if (ns.isAuth()) {
925			runningAuth = true;
926		} else {
927		    // nis/ldap is a special case
928		    // need to login to nis/ldap server
929		    if (ns.getNameService().equals("nis") == true ||
930			ns.getNameService().equals("ldap") == true) {
931
932                	try {
933                            if (!ns.isAuth()) {
934                        	pmUtility.doLogin(myTop, loadView.frame);
935				runningAuth = true;
936                            }
937                	} catch (pmUserCancelledException e) {
938                        	Debug.message(
939				    "CLNT:pmTop:user cancelled login");
940				runningAuth = false;
941                	} catch (pmGuiException e) {
942                        	Debug.message(
943                                    "CLNT:pmTop:login nis/ldap failed: " + e);
944				runningAuth = false;
945				pmMessageDialog m = new pmMessageDialog(
946				    loadView.frame,
947				    pmUtility.getResource("Error"),
948				    pmUtility.getResource(
949					"Required.login.failed."),
950				    myTop,
951				    "LoginFailed");
952				m.setVisible(true);
953                	} catch (Exception e) {
954                            Debug.message(
955                                "CLNT:pmTop:login nis/ldap failed: " + e);
956			    runningAuth = false;
957			    pmMessageDialog m = new pmMessageDialog(
958				    loadView.frame,
959				    pmUtility.getResource("Error"),
960				    pmUtility.getResource(
961					"Required.login.failed."),
962				    myTop,
963				    "LoginFailed");
964			    m.setVisible(true);
965                	}
966		    } else {
967			try {
968				ns.checkAuth();
969				runningAuth = true;
970			} catch (Exception ca) {
971			runningAuth = false;
972			    pmMessageDialog m = new pmMessageDialog(
973			    loadView.frame,
974			    pmUtility.getResource("Error"),
975			    pmUtility.getResource(
976			    "User.not.authorized.to.modify.this.namespace."),
977			    myTop,
978			    "AuthorizationFailed");
979			m.setVisible(true);
980			}
981		    }
982		}
983
984		if (!serverNS.equals(ns.getNameService())) {
985			deleteAllScreens();
986		}
987
988		// Change front panel as unauthorized to modify
989		if (!runningAuth) {
990			logCheck.setEnabled(false);
991			confirmCheck.setEnabled(false);
992			usePPD.setEnabled(false);
993			useLocalhost.setEnabled(false);
994			access.setEnabled(false);
995			local.setEnabled(false);
996			network.setEnabled(false);
997			modifyMenuItem.setEnabled(false);
998			deleteMenuItem.setEnabled(false);
999		} else {
1000			logCheck.setEnabled(true);
1001			confirmCheck.setEnabled(true);
1002			access.setEnabled(true);
1003			local.setEnabled(true);
1004			network.setEnabled(true);
1005			if (pmMisc.isppdCachefile())
1006				usePPD.setEnabled(true);
1007			else
1008				usePPD.setEnabled(false);
1009        		if (ns.getNameService().equals("system") == true) {
1010				useLocalhost.setEnabled(true);
1011				useLocalhost.setVisible(true);
1012			} else {
1013				useLocalhost.setVisible(false);
1014			}
1015		}
1016
1017	} else {
1018		runningAuth = false;
1019	}
1020
1021
1022        Debug.message("CLNT:  NEW ns.getNameService(): " +
1023                       ns.getNameService());
1024
1025    }
1026
1027    class topnsListener implements ItemListener {
1028        public topnsListener() {}
1029
1030        public void itemStateChanged(ItemEvent e) {
1031            Debug.message("CLNT:  hello from topnsListener" + e.getItem());
1032			if (e.getStateChange() == ItemEvent.SELECTED) {
1033				newNS = (String)e.getItem();
1034			}
1035        }
1036    }
1037
1038    public void pmsetdefaultpLabel() {
1039	try {
1040            defaultpLabel.setText(
1041                pmUtility.getResource("Default.Printer:") +
1042                " " + PrinterUtil.getDefaultPrinter(ns));
1043
1044		Debug.message(
1045			"CLNT: pmTop:pmsetdefaultpLabel(): default printer: " +
1046                          PrinterUtil.getDefaultPrinter(ns));
1047
1048	} catch (Exception e) {
1049		Debug.warning("CLNT: pmTop:getDefaultPrinter() caught " + e);
1050	}
1051    }
1052
1053    public boolean getLogOption() {
1054	return logCheck.getState();
1055    }
1056
1057    public void setLogOption(boolean val) {
1058	 logCheck.setState(val);
1059    }
1060
1061    public boolean getConfirmOption() {
1062	return confirmCheck.getState();
1063    }
1064
1065    public boolean getUsePPD() {
1066	return usePPD.getState();
1067    }
1068
1069    public boolean getUseLocalhost() {
1070	return useLocalhost.getState();
1071    }
1072
1073    public void doFind(String printer) {
1074    }
1075
1076    public void deleteAllScreens() {
1077
1078        if (accessView != null)
1079            accessView.pmScreendispose();
1080	accessView = null;
1081
1082        if (localinstallView != null)
1083            localinstallView.pmScreendispose();
1084	localinstallView = null;
1085
1086        if (networkinstallView != null)
1087            networkinstallView.pmScreendispose();
1088	networkinstallView = null;
1089
1090        if (modifyView != null)
1091            modifyView.pmScreendispose();
1092	modifyView = null;
1093
1094        if (loadView != null)
1095            loadView.pmScreendispose();
1096        loadView = null;
1097    }
1098
1099
1100    /*
1101     * enable/disable modify and delete items
1102     * this must be called when:
1103     *    . an existing printer is selected
1104     *    . the selection is disabled
1105     */
1106    void enableEditMenuItems(boolean state) {
1107        if (!runningAuth)
1108            return;
1109        modifyMenuItem.setEnabled(state);
1110        deleteMenuItem.setEnabled(state);
1111    }
1112
1113    /*
1114     * set the log/error state for the current operation
1115     */
1116    void setLogData(String cmd, String err, String warn) {
1117        cmdLog = cmd;
1118        errorLog = err;
1119        warningLog = warn;
1120    }
1121
1122    /*
1123     * display current log state for the specified action
1124     * if the cmdLog is empty nothing at all will be displayed!
1125     */
1126    void showLogData(String actionName) {
1127
1128	// Debug.info("CLNT: showLogData():actionName: " + actionName);
1129	// Debug.info("CLNT: showLogData():cmdLog: " + cmdLog);
1130
1131        if (cmdLog == null)
1132		return;
1133
1134        addToCommandLog(actionName + "\n");
1135
1136	// iterate over multiline cmds
1137	StringTokenizer st = new StringTokenizer(
1138			cmdLog, "\n\r", false);
1139	while (st.hasMoreTokens()) {
1140		addToCommandLog("% " + st.nextToken());
1141		addToCommandLog("\n");
1142	}
1143
1144        if (errorLog != null) {
1145		st = new StringTokenizer(errorLog, "\n\r", false);
1146		while (st.hasMoreTokens()) {
1147			addToCommandLog(st.nextToken());
1148			addToCommandLog("\n");
1149		}
1150	}
1151
1152        if (warningLog != null) {
1153		st = new StringTokenizer(warningLog, "\n\r", false);
1154		while (st.hasMoreTokens()) {
1155			addToCommandLog(st.nextToken());
1156			addToCommandLog("\n");
1157		}
1158	}
1159
1160        addToCommandLog("***\n");
1161    }
1162
1163    private void addToCommandLog(String s) {
1164        commandLog.addText(s);
1165    }
1166
1167    public void showHelpItem(String tag) {
1168        if (helpFrame != null)
1169	    helpFrame.showHelp(tag);
1170	else
1171	    Toolkit.getDefaultToolkit().beep();
1172    }
1173
1174    public void pmsetNSLabel() {
1175
1176	if (newNS.startsWith("files")) {
1177
1178	    nameserviceLabel.setText("    ");
1179	    Debug.message("CLNT: pmsetNSLabel:nameserviceLabel is : " +
1180		nameserviceLabel.getText());
1181
1182	    try {
1183		domainhostLabel.setText(
1184		pmUtility.getResource("Host:") + " " +
1185		host.getLocalHostName());
1186	    } catch (Exception e) {
1187		    Debug.warning(
1188			"CLNT: pmTop:getLocalHostName caught " + e);
1189	    }
1190
1191	} else {
1192		nameserviceLabel.setText(
1193		    pmUtility.getResource("Naming.Service:") + newNS);
1194		Debug.message(
1195		    "CLNT: pmsetNSLabel:nameserviceLabel is : " +
1196		    nameserviceLabel.getText());
1197
1198		try {
1199		    domainhostLabel.setText(
1200		    pmUtility.getResource("Domain:") + " " +
1201		    host.getDomainName());
1202		} catch (Exception e) {
1203		    Debug.warning(
1204			"CLNT: pmTop:getDomainName caught " + e);
1205		}
1206	}
1207    }
1208
1209	// Update the list of printers
1210	// Printer list will change if nameservice changes and when user
1211	// adds/deletes/changes printers
1212
1213    public void pmsetPrinterList() {
1214
1215        Debug.message("CLNT: pmsetPrinterList() ns is :" +
1216                       ns.getNameService());
1217
1218        try {
1219            listModel.insertlistTable(PrinterUtil.getPrinterList(ns),
1220                                      listModel.getColumnCount());
1221        } catch (Exception e) {
1222            Debug.warning("CLNT: pmTop:getPrinterList() caught " + e);
1223        }
1224
1225	listTable.clearSelection();
1226	scrollPane.getViewport().setView(listTable);
1227	scrollPane.revalidate();
1228	scrollPane.repaint();
1229    }
1230
1231
1232    // returns -1 if error, 0 otherwise
1233    protected static int parseArgs(String[] args) {
1234        int rv = 0;
1235
1236        for (int i = 0; i < args.length; ++i) {
1237            if (args[i].compareTo("-debugall") == 0)
1238                Debug.setDebugLevel(Debug.ALL);
1239            else if (args[i].compareTo("-debugnone") == 0)
1240                Debug.setDebugLevel(Debug.NONE);
1241            else if (args[i].compareTo("-debugwarn") == 0)
1242                Debug.setDebugLevel(Debug.WARNING);
1243            else if (args[i].compareTo("-debugerr") == 0)
1244                Debug.setDebugLevel(Debug.ERROR);
1245            else if (args[i].compareTo("-debugfatal") == 0)
1246                Debug.setDebugLevel(Debug.FATAL);
1247            else if (args[i].compareTo("-debugmsg") == 0)
1248                Debug.setDebugLevel(Debug.MESSAGE);
1249            else if (args[i].compareTo("-debuginfo") == 0)
1250                Debug.setDebugLevel(Debug.INFO);
1251        }
1252
1253        return rv;
1254    }
1255
1256    public static void main(String[] args) {
1257
1258        if (parseArgs(args) < 0)
1259            System.exit(-1);
1260
1261        // use pmFrame to get app icon
1262        pmFrame frame = new pmFrame(pmUtility.getResource("info_name"));
1263
1264	myTop = new pmTop(frame);
1265
1266	frame.addWindowListener(new WindowAdapter() {
1267		public void windowClosing(WindowEvent e) {
1268               		System.exit(0);
1269            	}
1270	});
1271
1272	frame.getContentPane().add("Center", myTop);
1273	frame.pack();
1274	frame.setVisible(true);
1275	frame.repaint();
1276
1277	pmLoad firstload = new pmLoad(myTop);
1278	myTop.loadView = firstload;
1279	firstload.Show();
1280
1281        aboutBox = new pmAboutBox();
1282        commandLog = new pmLogDisplay(myTop, "ShowCommandConsole");
1283        findFrame = new pmFindFrame(myTop);
1284
1285	/*
1286	 * Make sure to open the help frame after the about box,
1287	 * command log, and find frame windows have been opened.
1288	 * Otherwise it might cause null pointer exceptions as it
1289	 * takes a long time for the help frame to load.
1290	 */
1291        helpFrame = new pmHelpFrame();
1292
1293    }
1294
1295    // disable Enter action **for all JTextFields**
1296    static {
1297        JTextField f = new JTextField();
1298        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
1299        Keymap map = f.getKeymap();
1300        map.removeKeyStrokeBinding(enter);
1301    }
1302
1303}
1304