Package com.eteks.sweethome3d.model

Examples of com.eteks.sweethome3d.model.UserPreferences


   * Tests user preferences panel.
   */
  public void testUserPreferencesPanel()
       throws RecorderException, NoSuchFieldException, IllegalAccessException {
    // 0. Keep a copy of current preferences
    UserPreferences previousPreferences = new FileUserPreferences();
   
    // 1. Create default preferences for a user that uses centimeter
    Locale.setDefault(Locale.FRANCE);
    UserPreferences defaultPreferences = new DefaultUserPreferences();
    // Copy these preferences into system preferences
    UserPreferences preferences = new FileUserPreferences();
    preferences.setUnit(defaultPreferences.getLengthUnit());
    preferences.setRulersVisible(
        defaultPreferences.isRulersVisible());
    preferences.setGridVisible(
        defaultPreferences.isGridVisible());
    preferences.setMagnetismEnabled(
        defaultPreferences.isMagnetismEnabled());
    preferences.setFurnitureViewedFromTop(
        defaultPreferences.isFurnitureViewedFromTop());
    preferences.setFloorColoredOrTextured(
        defaultPreferences.isFurnitureViewedFromTop());
    preferences.setNewWallThickness(
        defaultPreferences.getNewWallThickness());
    preferences.setNewWallHeight(
        defaultPreferences.getNewWallHeight());
   
    // 2. Create a user preferences panel
    UserPreferencesController controller =
        new UserPreferencesController(preferences, new SwingViewFactory(), null);
    UserPreferencesPanel panel = (UserPreferencesPanel)controller.getView();
    JRadioButton centimeterRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "centimeterRadioButton");
    JRadioButton inchRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "inchRadioButton");
    JRadioButton meterRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "meterRadioButton");
    JRadioButton millimeterRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "millimeterRadioButton");
    JCheckBox    magnetismCheckBox =
        (JCheckBox)TestUtilities.getField(panel, "magnetismCheckBox");
    JCheckBox    rulersCheckBox =
        (JCheckBox)TestUtilities.getField(panel, "rulersCheckBox");
    JCheckBox    gridCheckBox =
        (JCheckBox)TestUtilities.getField(panel, "gridCheckBox");
    JRadioButton catalogIconRadioButton =
      (JRadioButton)TestUtilities.getField(panel, "catalogIconRadioButton");
    JRadioButton topViewRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "topViewRadioButton");
    JRadioButton monochromeRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "monochromeRadioButton");
    JRadioButton floorColorOrTextureRadioButton =
        (JRadioButton)TestUtilities.getField(panel, "floorColorOrTextureRadioButton");
    JSpinner newWallThicknessSpinner =
        (JSpinner)TestUtilities.getField(panel, "newWallThicknessSpinner");
    JSpinner newHomeWallHeightSpinner =
        (JSpinner)TestUtilities.getField(panel, "newWallHeightSpinner");
    // Check panel components value
    assertTrue("Centimeter radio button isn't selected", centimeterRadioButton.isSelected());
    assertFalse("Inch radio button is selected",  inchRadioButton.isSelected());
    assertFalse("Meter radio button is selected", meterRadioButton.isSelected());
    assertFalse("Millimeter radio button is selected", millimeterRadioButton.isSelected());
    assertTrue("Magnestism isn't selected", magnetismCheckBox.isSelected());
    assertTrue("Rulers isn't selected", rulersCheckBox.isSelected());
    assertTrue("Grid isn't selected", gridCheckBox.isSelected());
    assertTrue("Catalog icon radio button isn't selected", catalogIconRadioButton.isSelected());
    assertFalse("Top view button is selected",  topViewRadioButton.isSelected());
    assertTrue("Monochrome radio button isn't selected", monochromeRadioButton.isSelected());
    assertFalse("Floor color radio button is selected",  floorColorOrTextureRadioButton.isSelected());
    assertEquals("Wrong default thickness",
        newWallThicknessSpinner.getValue(), defaultPreferences.getNewWallThickness());
    assertEquals("Wrong default wall height",
        newHomeWallHeightSpinner.getValue(), defaultPreferences.getNewWallHeight());
   
    // 3. Change panel values
    inchRadioButton.setSelected(true);
    magnetismCheckBox.setSelected(false);
    rulersCheckBox.setSelected(false);
    gridCheckBox.setSelected(false);
    topViewRadioButton.setSelected(true);
    floorColorOrTextureRadioButton.setSelected(true);
    newWallThicknessSpinner.setValue(1);
    newHomeWallHeightSpinner.setValue(100);
   
    // 4. Retrieve panel values into preferences
    controller.modifyUserPreferences();
    // Check preferences value
    assertPreferencesEqual(LengthUnit.INCH, false, false, false,
        true, true,
        LengthUnit.inchToCentimeter(1),
        LengthUnit.inchToCentimeter(100),
        preferences);
   
    // 5. Save preferences and read them in an other system preferences object
    preferences.write();
    UserPreferences readPreferences = new FileUserPreferences();
    // Check if readPreferences and preferences have the same values
    assertPreferencesEqual(preferences.getLengthUnit(),
        preferences.isMagnetismEnabled(),
        preferences.isRulersVisible(),
        preferences.isGridVisible(),
View Full Code Here


   * Tests language changes on the GUI.
   */
  public void testLanguageChange() {
    Locale defaultLocale = Locale.getDefault();
    Locale.setDefault(Locale.US);
    UserPreferences preferences = new DefaultUserPreferences() {
      @Override
      public void write() throws RecorderException {
        // Ignore write requests
      }
    };

    Home home = new Home();
    Content imageContent = new URLContent(UserPreferencesPanelTest.class.getResource("resources/test.png"));
    home.setBackgroundImage(new BackgroundImage(imageContent, 1, 0, 1, 0, 1, 0, 0));

    SwingViewFactory viewFactory = new SwingViewFactory();
    FileContentManager contentManager = new FileContentManager(preferences);
    UndoableEditSupport undoableEditSupport = new UndoableEditSupport();
   
    for (String language : preferences.getSupportedLanguages()) {
      preferences.setLanguage(language);
      // Instantiate all views available in Sweet Home 3D
      HomeController homeController = new HomeController(home, preferences, viewFactory, contentManager);
      homeController.getView();
      preferences.setFurnitureCatalogViewedInTree(false);
      new FurnitureCatalogController(preferences.getFurnitureCatalog(), preferences, viewFactory, contentManager).getView();
      preferences.setFurnitureCatalogViewedInTree(true);
      new FurnitureCatalogController(preferences.getFurnitureCatalog(), preferences, viewFactory, contentManager).getView();
      new FurnitureController(home, preferences, viewFactory).getView();
      new PlanController(home, preferences, viewFactory, contentManager, undoableEditSupport).getView();
      new HomeController3D(home, preferences, viewFactory, contentManager, undoableEditSupport).getView();
     
      new PageSetupController(home, preferences, viewFactory, undoableEditSupport).getView();
View Full Code Here

  private static final String IGNORE_CACHE_PARAMETER = "ignoreCache";
  private static final String NAVIGATION_PANEL       = "navigationPanel";
 
  public ViewerHelper(final JApplet applet) {
    // Create default user preferences with no catalog
    final UserPreferences preferences = new UserPreferences() {
        @Override
        public void addLanguageLibrary(String languageLibraryName) throws RecorderException {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public boolean languageLibraryExists(String languageLibraryName) throws RecorderException {
          throw new UnsupportedOperationException();
        }

        @Override
        public void addFurnitureLibrary(String furnitureLibraryName) throws RecorderException {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public boolean furnitureLibraryExists(String furnitureLibraryName) throws RecorderException {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public boolean texturesLibraryExists(String name) throws RecorderException {
          throw new UnsupportedOperationException();
        }

        @Override
        public void addTexturesLibrary(String name) throws RecorderException {
          throw new UnsupportedOperationException();
        }

        @Override
        public void write() throws RecorderException {
          throw new UnsupportedOperationException();
        }
       
        @Override
        public boolean isNavigationPanelVisible() {
          return "true".equalsIgnoreCase(applet.getParameter(NAVIGATION_PANEL));
        }
      };
   
    // Create a view factory able to instantiate only a 3D view and a threaded task view
    final ViewFactory viewFactory = new ViewFactory() {
        public View createBackgroundImageWizardStepsView(BackgroundImage backgroundImage, UserPreferences preferences,
                                                         BackgroundImageWizardController backgroundImageWizardController) {
          throw new UnsupportedOperationException();
        }

        public View createFurnitureCatalogView(FurnitureCatalog catalog, UserPreferences preferences,
                                               FurnitureCatalogController furnitureCatalogController) {
          throw new UnsupportedOperationException();
        }

        public View createFurnitureView(Home home, UserPreferences preferences, FurnitureController furnitureController) {
          throw new UnsupportedOperationException();
        }

        public HelpView createHelpView(UserPreferences preferences, HelpController helpController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createHome3DAttributesView(UserPreferences preferences,
                                                     Home3DAttributesController home3DAttributesController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createHomeFurnitureView(UserPreferences preferences,
                                                  HomeFurnitureController homeFurnitureController) {
          throw new UnsupportedOperationException();
        }

        public HomeView createHomeView(Home home, UserPreferences preferences, HomeController homeController) {
          throw new UnsupportedOperationException();
        }

        public ImportedFurnitureWizardStepsView createImportedFurnitureWizardStepsView(CatalogPieceOfFurniture piece,
                    String modelName, boolean importHomePiece, UserPreferences preferences,
                    ImportedFurnitureWizardController importedFurnitureWizardController) {
          throw new UnsupportedOperationException();
        }

        public View createImportedTextureWizardStepsView(CatalogTexture texture, String textureName,
                                                         UserPreferences preferences,
                                                         ImportedTextureWizardController importedTextureWizardController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createLabelView(boolean modification, UserPreferences preferences,
                                          LabelController labelController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createPageSetupView(UserPreferences preferences, PageSetupController pageSetupController) {
          throw new UnsupportedOperationException();
        }

        public PlanView createPlanView(Home home, UserPreferences preferences, PlanController planController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createPrintPreviewView(Home home, UserPreferences preferences, HomeController homeController,
                                                 PrintPreviewController printPreviewController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createRoomView(UserPreferences preferences, RoomController roomController) {
          throw new UnsupportedOperationException();
        }

        public TextureChoiceView createTextureChoiceView(UserPreferences preferences,
                                                         TextureChoiceController textureChoiceController) {
          throw new UnsupportedOperationException();
        }

        public ThreadedTaskView createThreadedTaskView(String taskMessage, UserPreferences preferences,
                                                       ThreadedTaskController controller) {
          return new ThreadedTaskPanel(taskMessage, preferences, controller) {
              private boolean taskRunning;
 
              public void setTaskRunning(boolean taskRunning, View executingView) {
                if (taskRunning && !this.taskRunning) {
                  // Display task panel directly at applet center if it's empty
                  this.taskRunning = taskRunning;
                  JPanel contentPane = new JPanel(new GridBagLayout());
                  contentPane.add(this, new GridBagConstraints());
                  applet.setContentPane(contentPane);
                  applet.getRootPane().revalidate();
                }
              }
            };
        }

        public DialogView createUserPreferencesView(UserPreferences preferences,
                                                    UserPreferencesController userPreferencesController) {
          throw new UnsupportedOperationException();
        }

        public View createView3D(final Home home, UserPreferences preferences, final HomeController3D controller) {
          HomeComponent3D homeComponent3D = new HomeComponent3D(home, preferences, controller);
          // Add tab key to input map to change camera
          InputMap inputMap = homeComponent3D.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          inputMap.put(KeyStroke.getKeyStroke("SPACE"), "changeCamera");
          ActionMap actionMap = homeComponent3D.getActionMap();
          actionMap.put("changeCamera", new AbstractAction() {
              public void actionPerformed(ActionEvent ev) {
                if (home.getCamera() == home.getTopCamera()) {
                  controller.viewFromObserver();
                } else {
                  controller.viewFromTop();
                }
              }
            });
          return homeComponent3D;
        }

        public DialogView createWallView(UserPreferences preferences, WallController wallController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createWizardView(UserPreferences preferences, WizardController wizardController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createPhotoView(Home home, UserPreferences preferences, PhotoController photoController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createVideoView(Home home, UserPreferences preferences, VideoController videoController) {
          throw new UnsupportedOperationException();
        }

        public DialogView createCompassView(UserPreferences preferences, CompassController compassController) {
          throw new UnsupportedOperationException();
        }
      };

    // Force offscreen in 3D view under Plugin 2 and Mac OS X
    System.setProperty("com.eteks.sweethome3d.j3d.useOffScreen3DView",
        String.valueOf(OperatingSystem.isMacOSX()           
            && applet.getAppletContext() != null
            && applet.getAppletContext().getClass().getName().startsWith("sun.plugin2.applet.Plugin2Manager")));

    initLookAndFeel();

    addComponent3DRenderingErrorObserver(applet.getRootPane(), preferences);

    // Retrieve displayed home
    String homeUrlParameter = applet.getParameter(HOME_URL_PARAMETER);
    if (homeUrlParameter == null) {
      homeUrlParameter = "default.sh3d";
    }
    // Retrieve ignoreCache parameter value
    String ignoreCacheParameter = applet.getParameter(IGNORE_CACHE_PARAMETER);
    final boolean ignoreCache = ignoreCacheParameter != null
        && "true".equalsIgnoreCase(ignoreCacheParameter);
    try {
      final URL homeUrl = new URL(applet.getDocumentBase(), homeUrlParameter);
      // Read home in a threaded task
      Callable<Void> openTask = new Callable<Void>() {
            public Void call() throws RecorderException {
              // Read home with application recorder
              Home openedHome = readHome(homeUrl, ignoreCache);
              displayHome(applet.getRootPane(), openedHome, preferences, viewFactory);
              return null;
            }
          };
      ThreadedTaskController.ExceptionHandler exceptionHandler =
          new ThreadedTaskController.ExceptionHandler() {
            public void handleException(Exception ex) {
              if (!(ex instanceof InterruptedRecorderException)) {
                if (ex instanceof RecorderException) {
                  showError(applet.getRootPane(),
                      preferences.getLocalizedString(ViewerHelper.class, "openError", homeUrl));
                } else {
                  ex.printStackTrace();
                }
              }
            }
          };
      new ThreadedTaskController(openTask,
          preferences.getLocalizedString(ViewerHelper.class, "openMessage"), exceptionHandler,
          null, viewFactory).executeTask(null);
    } catch (MalformedURLException ex) {
      showError(applet.getRootPane(),
          preferences.getLocalizedString(ViewerHelper.class, "openError", homeUrlParameter));
      return;
    }
  }
View Full Code Here

    public TestFrame() {
      super("Home Plan Component Test");
      this.home = new Home();
      this.home.getCompass().setVisible(false);
      UserPreferences preferences = new DefaultUserPreferences();     
      ViewFactory viewFactory = new SwingViewFactory();
      this.homeController = new HomeController(home, preferences, viewFactory);
      JComponent homeView = (JComponent)this.homeController.getView();
      ActionMap actions = homeView.getActionMap();
      // Create buttons from HomePane actions map
View Full Code Here

    }
   
    public void propertyChange(PropertyChangeEvent ev) {
      // If plan component was garbage collected, remove this listener from preferences
      PlanComponent planComponent = this.planComponent.get();
      UserPreferences preferences = (UserPreferences)ev.getSource();
      UserPreferences.Property property = UserPreferences.Property.valueOf(ev.getPropertyName());
      if (planComponent == null) {
        preferences.removePropertyChangeListener(property, this);
      } else {
        switch (property) {
          case LANGUAGE :
          case UNIT :
            // Update format of tool tip text fields
            for (Map.Entry<PlanController.EditableProperty, JFormattedTextField> toolTipTextFieldEntry :
              planComponent.toolTipEditableTextFields.entrySet()) {
              updateToolTipTextFieldFormatterFactory(toolTipTextFieldEntry.getValue(),
                  toolTipTextFieldEntry.getKey(), preferences);
            }
            if (planComponent.horizontalRuler != null) {
              planComponent.horizontalRuler.repaint();
            }
            if (planComponent.verticalRuler != null) {
              planComponent.verticalRuler.repaint();
            }
            break;
          case WALL_PATTERN :
            planComponent.wallsPatternImageCache = null;
            break;
          case FURNITURE_VIEWED_FROM_TOP :
            if (planComponent.furnitureTopViewIconsCache != null
                && !preferences.isFurnitureViewedFromTop()) {
              planComponent.furnitureTopViewIconsCache = null;
            }
            break;
        }
        planComponent.repaint();
View Full Code Here

* @author Emmanuel Puybaret
*/
public class TransferHandlerTest extends ComponentTestFixture {
  public void testTransferHandler() throws ComponentSearchException, UnsupportedFlavorException,
                                           IOException, InterruptedException, InvocationTargetException {
    UserPreferences preferences = new DefaultUserPreferences();
    preferences.setFurnitureCatalogViewedInTree(true);
    ViewFactory viewFactory = new SwingViewFactory();
    Home home = new Home();
    home.getCompass().setVisible(false);
    final HomeController controller = new HomeController(home, preferences, viewFactory);
    JComponent homeView = (JComponent)controller.getView();
View Full Code Here

*/
public class HomeFurniturePanelTest extends ComponentTestFixture {
  public void testHomePieceOfFurniturePanel() throws ComponentSearchException, NoSuchFieldException, IllegalAccessException {
    // 1. Create default preferences for a user that uses centimeter
    Locale.setDefault(Locale.FRANCE);
    UserPreferences preferences = new DefaultUserPreferences();
    SwingViewFactory viewFactory = new SwingViewFactory();
    ContentManager contentManager = new FileContentManager(preferences);
    // Create a home and add a selected piece of furniture to it
    Home home = new Home();
    PieceOfFurniture firstPiece = preferences.getFurnitureCatalog().
        getCategories().get(0).getFurniture().get(0);
    HomePieceOfFurniture piece1 = new HomePieceOfFurniture(firstPiece);
    home.addPieceOfFurniture(piece1);
    home.setSelectedItems(Arrays.asList(new HomePieceOfFurniture [] {piece1}));

View Full Code Here

    assertFalse("Dialog still showing", dialog.isShowing());
  }

  public static void main(String [] args) {
    // Create a selected piece of furniture in a home and display it in a furniture panel
    UserPreferences preferences = new DefaultUserPreferences();
    Home home = new Home();
    PieceOfFurniture firstPiece = preferences.getFurnitureCatalog().
        getCategories().get(0).getFurniture().get(0);
    HomePieceOfFurniture piece1 = new HomePieceOfFurniture(firstPiece);
    home.addPieceOfFurniture(piece1);
    home.setSelectedItems(Arrays.asList(new HomePieceOfFurniture [] {piece1}));
   
View Full Code Here

* @author Emmanuel Puybaret
*/
public class PrintTest extends ComponentTestFixture {
  public void testPageSetupAndPrintPreview() throws ComponentSearchException, InterruptedException,
      NoSuchFieldException, IllegalAccessException, InvocationTargetException, IOException {
    UserPreferences preferences = new DefaultUserPreferences();
    ViewFactory viewFactory = new SwingViewFactory();
    Home home = new Home();
    ContentManager contentManager = new FileContentManager(preferences) {
        @Override
        public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) {
          String os = System.getProperty("os.name");
          if (OperatingSystem.isMacOSX()) {
            // Let's pretend the OS isn't Mac OS X to get a JFileChooser instance that works better in test
            System.setProperty("os.name", "dummy");
          }
          try {
            return super.showSaveDialog(parentView, dialogTitle, contentType, name);
          } finally {
            System.setProperty("os.name", os);
          }
        }
      };
    final HomeController controller =
        new HomeController(home, preferences, viewFactory, contentManager);

    // 1. Create a frame that displays a home view
    JFrame frame = new JFrame("Home Print Test");   
    frame.add((JComponent)controller.getView());
    frame.pack();

    // Show home frame
    showWindow(frame);
    JComponentTester tester = new JComponentTester();
    tester.waitForIdle();
    // Add a piece of furniture to home
    List<CatalogPieceOfFurniture> selectedPieces = Arrays.asList(
        new CatalogPieceOfFurniture [] {preferences.getFurnitureCatalog().getCategories().get(0).getFurniture().get(0)});
    controller.getFurnitureCatalogController().setSelectedFurniture(selectedPieces);
    tester.invokeAndWait(new Runnable() {
      public void run() {
        runAction(controller, HomePane.ActionType.ADD_HOME_FURNITURE);
      }
    });
    // Check home contains one piece
    assertEquals("Home doesn't contain any furniture", 1, home.getFurniture().size());
   
    // 2. Edit page setup dialog box
    tester.invokeLater(new Runnable() {
        public void run() {
          // Display dialog box later in Event Dispatch Thread to avoid blocking test thread
          runAction(controller, HomePane.ActionType.PAGE_SETUP);
        }
      });
    // Wait for page setup to be shown
    tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
        PageSetupPanel.class, "pageSetup.title"));
    // Check dialog box is displayed
    JDialog pageSetupDialog = (JDialog)TestUtilities.findComponent(
        frame, JDialog.class);
    assertTrue("Page setup dialog not showing", pageSetupDialog.isShowing());
    // Retrieve PageSetupPanel components
    PageSetupPanel pageSetupPanel = (PageSetupPanel)TestUtilities.findComponent(
        frame, PageSetupPanel.class);
    JCheckBox furniturePrintedCheckBox =
        (JCheckBox)TestUtilities.getField(pageSetupPanel, "furniturePrintedCheckBox");
    JCheckBox planPrintedCheckBox =
        (JCheckBox)TestUtilities.getField(pageSetupPanel, "planPrintedCheckBox");;
    JCheckBox view3DPrintedCheckBox =
        (JCheckBox)TestUtilities.getField(pageSetupPanel, "view3DPrintedCheckBox");
    // Check default edited values
    assertTrue("Furniture printed not checked", furniturePrintedCheckBox.isSelected());
    assertTrue("Plan printed not checked", planPrintedCheckBox.isSelected());
    assertTrue("View 3D printed not checked", view3DPrintedCheckBox.isSelected());
   
    // 3. Change dialog box values
    planPrintedCheckBox.setSelected(false);
    // Click on Ok in dialog box
    final JOptionPane pageSetupOptionPane = (JOptionPane)TestUtilities.findComponent(
        pageSetupDialog, JOptionPane.class);
    tester.invokeAndWait(new Runnable() {
        public void run() {
          // Select Ok option to hide dialog box in Event Dispatch Thread
          pageSetupOptionPane.setValue(JOptionPane.OK_OPTION);
        }
      });
    assertFalse("Page setup dialog still showing", pageSetupDialog.isShowing());
    PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
    // Check home print attributes are modified accordingly
    assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home);
   
    // 4. Undo changes
    runAction(controller, HomePane.ActionType.UNDO);
    // Check home attributes have previous values
    assertEquals("Home print set", null, home.getPrint());
    // Redo
    runAction(controller, HomePane.ActionType.REDO);
    // Check home attributes are modified accordingly
    assertHomePrintEqualPrintAttributes(pageFormat, true, false, true, home);
   
    // 5. Show print preview dialog box
    tester.invokeLater(new Runnable() {
        public void run() {
          // Display dialog box later in Event Dispatch Thread to avoid blocking test thread
          runAction(controller, HomePane.ActionType.PRINT_PREVIEW);
        }
      });
    // Wait for print preview to be shown
    tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
        PrintPreviewPanel.class, "printPreview.title"));
    // Check dialog box is displayed
    JDialog printPreviewDialog = (JDialog)new BasicFinder().find(frame,
        new ClassMatcher (JDialog.class, true));
    assertTrue("Print preview dialog not showing", printPreviewDialog.isShowing());
    // Retrieve PageSetupPanel components
    PrintPreviewPanel printPreviewPanel = (PrintPreviewPanel)TestUtilities.findComponent(
        frame, PrintPreviewPanel.class);
    JToolBar toolBar =
        (JToolBar)TestUtilities.getField(printPreviewPanel, "toolBar");
    JButton previousButton = (JButton)toolBar.getComponent(0);
    final JButton nextButton = (JButton)toolBar.getComponent(1);
    HomePrintableComponent printableComponent =
        (HomePrintableComponent)TestUtilities.getField(printPreviewPanel, "printableComponent");;
    // Check if buttons are enabled and if printable component displays the first page
    assertFalse("Previous button is enabled", previousButton.isEnabled());
    assertTrue("Next button is disabled", nextButton.isEnabled());
    assertEquals("Printable component doesn't display first page", 0, printableComponent.getPage());
    assertEquals("Wrong printable component page count", 2, printableComponent.getPageCount());
   
    // 6. Click on next page button
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nextButton.doClick();
        }
      });
    // Check if buttons are enabled and if printable component displays the second page
    assertTrue("Previous button is enabled", previousButton.isEnabled());
    assertFalse("Next button is disabled", nextButton.isEnabled());
    assertEquals("Printable component doesn't display second page", 1, printableComponent.getPage());
   
    // Click on Ok in dialog box
    final JOptionPane printPreviewOptionPane = (JOptionPane)TestUtilities.findComponent(
        printPreviewDialog, JOptionPane.class);
    tester.invokeAndWait(new Runnable() {
        public void run() {
          // Select Ok option to hide dialog box in Event Dispatch Thread
          printPreviewOptionPane.setValue(JOptionPane.OK_OPTION);
        }
      });
    assertFalse("Print preview dialog still showing", printPreviewDialog.isShowing());
   
    // 7. Check the created PDF file doesn't exist
    String pdfFileBase = "testsdfghjk";
    File pdfFile = new File(pdfFileBase + ".pdf");
    assertFalse("PDF file already exists, delete it first", pdfFile.exists());
    // Show print to PDF dialog box
    tester.invokeLater(new Runnable() {
        public void run() {
          // Display dialog box later in Event Dispatch Thread to avoid blocking test thread
          runAction(controller, HomePane.ActionType.PRINT_TO_PDF);
        }
      });
    // Wait for print to PDF file chooser to be shown
    tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
        HomePane.class, "printToPDFDialog.title"));
    // Check dialog box is displayed
    final Dialog printToPdfDialog = (Dialog)new BasicFinder().find(frame,
        new ClassMatcher (Dialog.class, true));
    assertTrue("Print to pdf dialog not showing", printToPdfDialog.isShowing());
View Full Code Here

*/
public class ImportedFurnitureWizardTest extends ComponentTestFixture {
  public void testImportFurnitureWizard() throws ComponentSearchException, InterruptedException,
      NoSuchFieldException, IllegalAccessException, InvocationTargetException {
    String language = Locale.getDefault().getLanguage();
    final UserPreferences preferences = new FileUserPreferences();
    // Ensure we use default language and centimeter unit
    preferences.setLanguage(language);
    preferences.setUnit(LengthUnit.CENTIMETER);
    final ViewFactory viewFactory = new SwingViewFactory();
    final URL testedModelName = ImportedFurnitureWizardTest.class.getResource("resources/test.obj");
    // Create a dummy content manager
    final ContentManager contentManager = new ContentManager() {
      public Content getContent(String contentName) throws RecorderException {
        try {
          // Let's consider contentName is a URL
          return new URLContent(new URL(contentName));
        } catch (IOException ex) {
          fail();
          return null;
        }
      }

      public String getPresentationName(String contentName, ContentType contentType) {
        return "test";
      }

      public boolean isAcceptable(String contentName, ContentType contentType) {
        return true;
      }

      public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) {
        // Return tested model name URL
        return testedModelName.toString();
      }

      public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) {
        return null;
      }     
    };
    Home home = new Home();
    final HomeController controller =
        new HomeController(home, preferences, viewFactory, contentManager);
    final JComponent homeView = (JComponent)controller.getView();
    final List<CatalogPieceOfFurniture> addedCatalogFurniture = new ArrayList<CatalogPieceOfFurniture>();
    preferences.getFurnitureCatalog().addFurnitureListener(new CollectionListener<CatalogPieceOfFurniture>() {
        public void collectionChanged(CollectionEvent<CatalogPieceOfFurniture> ev) {
          addedCatalogFurniture.add(ev.getItem());
        }
      });

    // 1. Create a frame that displays a home view
    JFrame frame = new JFrame("Imported Furniture Wizard Test");   
    frame.add(homeView);
    frame.pack();

    // Show home plan frame
    showWindow(frame);
    JComponentTester tester = new JComponentTester();
    tester.waitForIdle();   

    // 2. Transfer focus to plan view
    ((JComponent)controller.getPlanController().getView()).requestFocusInWindow();     
    tester.waitForIdle();   

    // Check plan view has focus
    assertTrue("Plan component doesn't have the focus",
        ((JComponent)controller.getPlanController().getView()).isFocusOwner());
    // Open wizard to import a test object (1 width x 2 depth x 3 height) in plan
    tester.invokeLater(new Runnable() {
        public void run() {
          // Display dialog box later in Event Dispatch Thread to avoid blocking test thread
          homeView.getActionMap().get(HomePane.ActionType.IMPORT_FURNITURE).actionPerformed(null);
        }
      });
    // Wait for import furniture view to be shown
    tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
        ImportedFurnitureWizardController.class, "importFurnitureWizard.title"));
    // Check dialog box is displayed
    JDialog wizardDialog = (JDialog)TestUtilities.findComponent(frame, JDialog.class);
    assertTrue("Wizard view dialog not showing", wizardDialog.isShowing());

    // Retrieve ImportedFurnitureWizardStepsPanel components
    ImportedFurnitureWizardStepsPanel panel = (ImportedFurnitureWizardStepsPanel)TestUtilities.findComponent(
        frame, ImportedFurnitureWizardStepsPanel.class);
    final JButton modelChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "modelChoiceOrChangeButton");
    final JButton turnLeftButton = (JButton)TestUtilities.getField(panel, "turnLeftButton");
    final JButton turnDownButton = (JButton)TestUtilities.getField(panel, "turnDownButton");
    JCheckBox backFaceShownCheckBox = (JCheckBox)TestUtilities.getField(panel, "backFaceShownCheckBox");
    final JTextField nameTextField = (JTextField)TestUtilities.getField(panel, "nameTextField");
    final JCheckBox addToCatalogCheckBox = (JCheckBox)TestUtilities.getField(panel, "addToCatalogCheckBox");
    final JComboBox categoryComboBox = (JComboBox)TestUtilities.getField(panel, "categoryComboBox");
    final JSpinner widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
    JSpinner heightSpinner = (JSpinner)TestUtilities.getField(panel, "heightSpinner");
    JSpinner depthSpinner = (JSpinner)TestUtilities.getField(panel, "depthSpinner");
    final JCheckBox keepProportionsCheckBox = (JCheckBox)TestUtilities.getField(panel, "keepProportionsCheckBox");
    JSpinner elevationSpinner = (JSpinner)TestUtilities.getField(panel, "elevationSpinner");
    JCheckBox movableCheckBox = (JCheckBox)TestUtilities.getField(panel, "movableCheckBox");
    JCheckBox doorOrWindowCheckBox = (JCheckBox)TestUtilities.getField(panel, "doorOrWindowCheckBox");
    ColorButton colorButton = (ColorButton)TestUtilities.getField(panel, "colorButton");
    final JButton clearColorButton = (JButton)TestUtilities.getField(panel, "clearColorButton");
   
    // Check current step is model
    tester.waitForIdle();
    assertStepShowing(panel, true, false, false, false);   
   
    // 3. Choose tested model
    String modelChoiceOrChangeButtonText = modelChoiceOrChangeButton.getText();
    tester.invokeAndWait(new Runnable() {
        public void run() {
          modelChoiceOrChangeButton.doClick();
        }
      });
    // Wait 1 s to let time to Java 3D to load the model
    Thread.sleep(1000);
    // Check choice button text changed
    assertFalse("Choice button text didn't change",
        modelChoiceOrChangeButtonText.equals(modelChoiceOrChangeButton.getText()));
    // Click on next button
    WizardPane view = (WizardPane)TestUtilities.findComponent(frame, WizardPane.class);
    // Retrieve wizard view next button
    final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton");
    assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());   
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nextFinishOptionButton.doClick();
        }
      });
    // Check current step is rotation
    assertStepShowing(panel, false, true, false, false);   
    // Check back face shown check box isn't selected by default
    assertFalse("Back face shown check box is selected", backFaceShownCheckBox.isSelected());
   
    // 4. Click on left button
    float width = (Float)widthSpinner.getValue();
    float depth = (Float)depthSpinner.getValue();
    float height = (Float)heightSpinner.getValue();
    tester.invokeAndWait(new Runnable() {
        public void run() {
          turnLeftButton.doClick();
        }
      });
    // Check depth and width values were swapped
    float newWidth = (Float)widthSpinner.getValue();
    float newDepth = (Float)depthSpinner.getValue();
    float newHeight = (Float)heightSpinner.getValue();
    TestUtilities.assertEqualsWithinEpsilon("Incorrect width", depth, newWidth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect depth", width, newDepth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect height", height, newHeight, 1E-3f);
    // Click on down button
    width = newWidth;
    depth = newDepth;
    height = newHeight;
    tester.invokeAndWait(new Runnable() {
        public void run() {
          turnDownButton.doClick();
        }
      });
    // Check height and depth values were swapped
    newWidth = (Float)widthSpinner.getValue();
    newDepth = (Float)depthSpinner.getValue();
    newHeight = (Float)heightSpinner.getValue();
    TestUtilities.assertEqualsWithinEpsilon("Incorrect width", width, newWidth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect depth", height, newDepth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect height", depth, newHeight, 1E-3f);
   
    // 5. Click on next button
    assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nextFinishOptionButton.doClick();
        }
      });
    // Check current step is attributes
    assertStepShowing(panel, false, false, true, false);   
       
    // 6. Check default furniture name is the presentation name proposed by content manager
    assertEquals("Wrong default name"
        contentManager.getPresentationName(testedModelName.toString(), ContentManager.ContentType.MODEL),
        nameTextField.getText());
    // Check Add to catalog check box isn't selected and category combo box
    // is disabled when furniture is imported in home
    assertFalse("Add to catalog check box is selected", addToCatalogCheckBox.isSelected());
    assertFalse("Category combo box isn't disabled", categoryComboBox.isEnabled());
    // Check default category is first category 
    final FurnitureCategory firstCategory = preferences.getFurnitureCatalog().getCategories().get(0);
    assertEquals("Wrong default category", firstCategory, categoryComboBox.getSelectedItem());
    // Rename furniture with the name of the catalog first piece
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nameTextField.setText(firstCategory.getFurniture().get(0).getName());
        }
      });
    // Check next button is enabled
    assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
    // Select Add to catalog check box
    tester.invokeAndWait(new Runnable() {
        public void run() {
          addToCatalogCheckBox.setSelected(true);
        }
      });
    // Check next button is disabled because imported furniture has a wrong name
    assertFalse("Next button isn't disabled", nextFinishOptionButton.isEnabled());
    // Rename furniture and its category
    final String pieceTestName = "#@" + System.currentTimeMillis() + "@#";
    final String categoryTestName = "sdfghjkl";
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nameTextField.setText(pieceTestName);
          categoryComboBox.getEditor().selectAll();
        }
      });
    tester.actionKeyString(categoryComboBox.getEditor().getEditorComponent(), categoryTestName);   
    // Check next button is enabled again
    assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
   
    // 7. Check keep proportions check box is selected by default
    assertTrue("Keep proportions check box isn't selected", keepProportionsCheckBox.isSelected());
    // Change width with a value 10 times greater
    width = newWidth;
    depth = newDepth;
    height = newHeight;
    final float enteredWidth = newWidth * 10;
    tester.invokeAndWait(new Runnable() {
        public void run() {
          widthSpinner.setValue(enteredWidth);
        }
      });
    // Check height and depth values are 10 times greater
    newWidth = (Float)widthSpinner.getValue();
    newDepth = (Float)depthSpinner.getValue();
    newHeight = (Float)heightSpinner.getValue();
    TestUtilities.assertEqualsWithinEpsilon("Incorrect width", 10 * width, newWidth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect depth", 10 * depth, newDepth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect height", 10 * height, newHeight, 1E-3f);
    // Deselect keep proportions check box
    tester.invokeAndWait(new Runnable() {
        public void run() {
          keepProportionsCheckBox.setSelected(false);
        }
      });      
    // Change width with a value 2 times greater
    width = newWidth;
    depth = newDepth;
    height = newHeight;
    final float twiceValue = newWidth * 2;
    tester.invokeAndWait(new Runnable() {
        public void run() {
          widthSpinner.setValue(twiceValue);
        }
      });
    // Check height and depth values didn't change
    newWidth = (Float)widthSpinner.getValue();
    newDepth = (Float)depthSpinner.getValue();
    newHeight = (Float)heightSpinner.getValue();
    TestUtilities.assertEqualsWithinEpsilon("Incorrect width", 2 * width, newWidth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect depth", depth, newDepth, 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect height", height, newHeight, 1E-3f);

    // 8. Change elevation, movable, door or window, color default values
    assertEquals("Wrong default elevation", 0f, (Float)elevationSpinner.getValue());
    elevationSpinner.setValue(10);
    assertTrue("Movable check box isn't selected", movableCheckBox.isSelected());
    movableCheckBox.setSelected(false);
    assertFalse("Door or window check box is selected", doorOrWindowCheckBox.isSelected());
    doorOrWindowCheckBox.setSelected(true);
    assertEquals("Wrong default color", null, colorButton.getColor());
    assertFalse("Clear color button isn't disabled", clearColorButton.isEnabled());
    // Change color
    colorButton.setColor(0x000000);
    // Check clear color button is enabled
    assertTrue("Clear color button isn't enabled", clearColorButton.isEnabled());
    // Click on clear color button
    tester.invokeAndWait(new Runnable() {
        public void run() {
          clearColorButton.doClick();
        }
      });
    // Check color is null and clear color button is disabled
    assertEquals("Wrong color", null, colorButton.getColor());
    assertFalse("Clear color button isn't disabled", clearColorButton.isEnabled());
    // 9. Click on next button
    tester.invokeAndWait(new Runnable() {
        public void run() {
          nextFinishOptionButton.doClick();
        }
      });
    // Check current step is icon
    assertStepShowing(panel, false, false, false, true);   
    tester.invokeAndWait(new Runnable() {
        public void run() {
          // Click on Finish to hide dialog box in Event Dispatch Thread
          nextFinishOptionButton.doClick();
        }
      });
   
    // 10. Check the matching new catalog piece of furniture was created
    List<CatalogPieceOfFurniture> selectedCatalogFurniture =
        controller.getFurnitureCatalogController().getSelectedFurniture();
    assertEquals("Wrong selected furniture count in catalog", 0, selectedCatalogFurniture.size());
    assertEquals("Incorrect count of created catalog piece", 1, addedCatalogFurniture.size());   
    CatalogPieceOfFurniture catalogPiece = addedCatalogFurniture.get(0);
    assertEquals("Wrong catalog piece name", pieceTestName, catalogPiece.getName());
    assertEquals("Wrong catalog piece category name", categoryTestName, catalogPiece.getCategory().getName());
    assertTrue("Catalog doesn't contain new piece",
        preferences.getFurnitureCatalog().getCategories().contains(catalogPiece.getCategory()));
    TestUtilities.assertEqualsWithinEpsilon("Incorrect width", newWidth, catalogPiece.getWidth(), 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect depth", newDepth, catalogPiece.getDepth(), 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect height", newHeight, catalogPiece.getHeight(), 1E-3f);
    TestUtilities.assertEqualsWithinEpsilon("Incorrect elevation", 10, catalogPiece.getElevation(), 1E-3f);
    assertFalse("Catalog piece is movable", catalogPiece.isMovable());
    assertTrue("Catalog piece isn't a door or window", catalogPiece.isDoorOrWindow());
    assertEquals("Wrong catalog piece color", null, catalogPiece.getColor());
    assertTrue("Catalog piece isn't modifiable", catalogPiece.isModifiable());
   
    // Check a new home piece of furniture was created and it's the selected piece in home
    List<Selectable> homeSelectedItems = home.getSelectedItems();
    assertEquals("Wrong selected furniture count in home", 1, homeSelectedItems.size());
    HomePieceOfFurniture homePiece = (HomePieceOfFurniture)homeSelectedItems.get(0);
    assertEquals("Wrong home piece name", pieceTestName, homePiece.getName());
   
    // 11. Transfer focus to tree
    JComponent catalogView = (JComponent)controller.getFurnitureCatalogController().getView();
    tester.focus(catalogView);       
    // Check plan view has focus
    assertTrue("Catalog tree doesn't have the focus", catalogView.isFocusOwner());
    // Select the piece added to catalog
    controller.getFurnitureCatalogController().setSelectedFurniture(addedCatalogFurniture);
    // Delete new catalog piece of furniture
    final Action deleteAction = homeView.getActionMap().get(HomePane.ActionType.DELETE);
    assertTrue("Delete action isn't enable", deleteAction.isEnabled());
    tester.invokeLater(new Runnable() {
        public void run() {
          deleteAction.actionPerformed(null);
        }
      });
    // Wait for confirm dialog to be shown
    tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
        HomePane.class, "confirmDeleteCatalogSelection.title"));
    // Find displayed dialog box
    JDialog confirmDeleteCatalogSelectionDialog = (JDialog)new BasicFinder().find(frame,
        new ClassMatcher (JDialog.class, true));
    // Click on Ok in dialog box
    final JOptionPane optionPane = (JOptionPane)TestUtilities.findComponent(
        confirmDeleteCatalogSelectionDialog, JOptionPane.class);
    tester.invokeAndWait(new Runnable() {
        public void run() {
          // Select delete option to hide dialog box in Event Dispatch Thread
          optionPane.setValue(preferences.getLocalizedString(
              HomePane.class, "confirmDeleteCatalogSelection.delete"));
        }
      });
    // Check selection is empty
    selectedCatalogFurniture = controller.getFurnitureCatalogController().getSelectedFurniture();
    assertTrue("Catalog selected furniture isn't empty", selectedCatalogFurniture.isEmpty());
    // Check catalog doesn't contain the new piece
    assertFalse("Piece is still in catalog",
        preferences.getFurnitureCatalog().getCategories().contains(catalogPiece.getCategory()));
    // Check home piece of furniture is still in home and selected
    assertTrue("Home piece isn't in home", home.getFurniture().contains(homePiece));
    assertTrue("Home piece isn't selected", home.getSelectedItems().contains(homePiece));
   
    // 12. Undo furniture creation in home
View Full Code Here

TOP

Related Classes of com.eteks.sweethome3d.model.UserPreferences

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.