Example #1
0
        protected override void OnClosing(CancelEventArgs e)
        {
            if (!this.finished)
            {
                string       title   = PdnInfo.GetBareProductName();
                string       message = PdnResources.GetString("SetupWizard.CancelDialog.Message");
                DialogResult result  = MessageBox.Show(this, message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }

            base.OnClosing(e);
        }
Example #2
0
 protected override void OnShown(EventArgs e)
 {
     this.SetTitleText();
     base.OnShown(e);
     if (PdnInfo.IsExpired)
     {
         foreach (Form form in Application.OpenForms)
         {
             form.Enabled = false;
         }
         TaskButton   button      = new TaskButton(PdnResources.GetImageResource("Icons.MenuUtilitiesCheckForUpdatesIcon.png").Reference, PdnResources.GetString("ExpiredTaskDialog.CheckForUpdatesTB.ActionText"), PdnResources.GetString("ExpiredTaskDialog.CheckForUpdatesTB.ExplanationText"));
         TaskButton   button2     = new TaskButton(PdnResources.GetImageResource("Icons.MenuHelpPdnWebsiteIcon.png").Reference, PdnResources.GetString("ExpiredTaskDialog.GoToWebSiteTB.ActionText"), PdnResources.GetString("ExpiredTaskDialog.GoToWebSiteTB.ExplanationText"));
         TaskButton   button3     = new TaskButton(PdnResources.GetImageResource("Icons.CancelIcon.png").Reference, PdnResources.GetString("ExpiredTaskDialog.DoNotCheckForUpdatesTB.ActionText"), PdnResources.GetString("ExpiredTaskDialog.DoNotCheckForUpdatesTB.ExplanationText"));
         TaskButton[] buttonArray = new TaskButton[] { button, button2, button3 };
         TaskDialog   dialog1     = new TaskDialog {
             Icon                  = base.Icon,
             Title                 = PdnInfo.FullAppName,
             TaskImage             = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference,
             ScaleTaskImageWithDpi = true,
             IntroText             = PdnResources.GetString("ExpiredTaskDialog.InfoText"),
             TaskButtons           = buttonArray,
             AcceptButton          = button,
             CancelButton          = button3,
             PixelWidth96Dpi       = 450
         };
         TaskButton button4 = dialog1.Show(this);
         if (button4 == button)
         {
             UpdatesService.Instance.PerformUpdateCheck();
         }
         else if (button4 == button2)
         {
             PdnInfo.LaunchWebSite(this, "redirect/pdnexpired.html");
         }
         base.Close();
     }
     if (this.appWorkspace.ActiveDocumentWorkspace != null)
     {
         this.appWorkspace.ActiveDocumentWorkspace.Focus();
     }
     else
     {
         this.appWorkspace.Focus();
     }
 }
Example #3
0
        public IntroPage()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            string expireTextFormat = PdnResources.GetString("SetupWizard.IntroPage.ExpirationWarning.Format");
            string expireText;

            if (PdnInfo.IsFinalBuild)
            {
                expireText = string.Empty;
            }
            else
            {
                expireText = string.Format(expireTextFormat, PdnInfo.ExpirationDate.ToLongDateString());
            }

            string introFormat    = PdnResources.GetString("SetupWizard.IntroPage.IntroText.Text.Format");
            string appNameWithTag = PdnInfo.GetBareProductName();
            string intro          = string.Format(introFormat, appNameWithTag);

            this.introText.Text = intro;

            this.quickRB.Text           = PdnResources.GetString("SetupWizard.IntroPage.QuickRB.Text");
            this.quickDescription.Text  = PdnResources.GetString("SetupWizard.IntroPage.QuickDescription.Text");
            this.customRB.Text          = PdnResources.GetString("SetupWizard.IntroPage.CustomRB.Text");
            this.customDescription.Text = PdnResources.GetString("SetupWizard.IntroPage.CustomDescription.Text");

            if (IntroPage.UserChoseQuickSetup)
            {
                this.quickRB.Checked = true;
            }
            else
            {
                this.customRB.Checked = true;
            }

            string format            = InvariantStrings.CopyrightFormat;
            string allRightsReserved = PdnResources.GetString("Application.Copyright.AllRightsReserved");
            string copyright         = string.Format(CultureInfo.CurrentCulture, format, allRightsReserved);

            this.copyrightLabel.Text = copyright;
        }
Example #4
0
        public override void PerformAction(AppWorkspace appWorkspace)
        {
            string email         = InvariantStrings.FeedbackEmail;
            string subjectFormat = PdnResources.GetString("SendFeedback.Email.Subject.Format");
            string subject       = string.Format(subjectFormat, PdnInfo.GetFullAppName());
            string body          = PdnResources.GetString("SendFeedback.Email.Body");
            string launchMe      = GetEmailLaunchString(email, subject, body);

            launchMe = launchMe.Substring(0, Math.Min(1024, launchMe.Length));

            try
            {
                Process.Start(launchMe);
            }

            catch (Exception)
            {
                Utility.ErrorBox(appWorkspace, PdnResources.GetString("LaunchLink.Error"));
            }
        }
Example #5
0
        public InstallingPage()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            string introFormat = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Installing.Format");

            this.appName        = PdnInfo.GetBareProductName();
            this.installingText = string.Format(introFormat, appName);

            this.uninstallingText = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Uninstalling");
            this.optimizingText   = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Optimizing");

            this.pdnDonateBannerImage = new Bitmap(bannerSize.Width, bannerSize.Height, PixelFormat.Format24bppRgb);

            using (Graphics g = Graphics.FromImage(this.pdnDonateBannerImage))
            {
                RenderPdnDonateBannerImage(g, new Rectangle(Point.Empty, this.pdnDonateBannerImage.Size));
            }

            this.topBanner.Image = this.pdnDonateBannerImage;
            this.topBanner.Tag   = InvariantStrings.DonateUrlSetup;
            this.toolTip.SetToolTip(this.topBanner, InvariantStrings.DonateUrlSetup);

            Image  mirrorImage;
            string mirrorClickUrl;

            LoadMirrorInfo(out mirrorImage, out mirrorClickUrl);

            if (mirrorImage != null && mirrorClickUrl != null)
            {
                this.bottomBanner.Image = mirrorImage;
                this.bottomBanner.Tag   = mirrorClickUrl;
                this.toolTip.SetToolTip(this.bottomBanner, mirrorClickUrl);
            }
        }
Example #6
0
        private static void CheckForUpdates(
            out PdnVersionManifest manifestResult,
            out int latestVersionIndexResult,
            out Exception exception)
        {
            exception = null;
            PdnVersionManifest manifest = null;

            manifestResult           = null;
            latestVersionIndexResult = -1;

            int retries = 2;

            while (retries > 0)
            {
                try
                {
                    manifest = GetUpdatesManifest(out exception);
                    retries  = 0;
                }

                catch (Exception ex)
                {
                    exception = ex;
                    --retries;

                    if (retries == 0)
                    {
                        manifest = null;
                    }
                }
            }

            if (manifest != null)
            {
                int stableIndex = manifest.GetLatestStableVersionIndex();
                int betaIndex   = manifest.GetLatestBetaVersionIndex();

                // Check for betas as well?
                bool checkForBetas = ("1" == Settings.SystemWide.GetString(PdnSettings.AlsoCheckForBetas, "0"));

                // Figure out which version we want to compare against the current version
                int latestIndex = stableIndex;

                if (checkForBetas)
                {
                    // If they like betas, and if the beta is newer than the latest stable release,
                    // then offer it to them.
                    if (betaIndex != -1 &&
                        (stableIndex == -1 || manifest.VersionInfos[betaIndex].Version >= manifest.VersionInfos[stableIndex].Version))
                    {
                        latestIndex = betaIndex;
                    }
                }

                // Now compare that version against the current version
                if (latestIndex != -1)
                {
                    if (PdnInfo.IsTestMode ||
                        manifest.VersionInfos[latestIndex].Version > PdnInfo.GetVersion())
                    {
                        manifestResult           = manifest;
                        latestVersionIndexResult = latestIndex;
                    }
                }
            }
        }
Example #7
0
 private void MenuHelpPlugins_Click(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(AppWorkspace, InvariantStrings.PluginsPageHelpPage);
 }
Example #8
0
 private void MenuHelpPdnWebsite_Click(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(AppWorkspace, InvariantStrings.WebsitePageHelpMenu);
 }
Example #9
0
        private void DoInstallation()
        {
            WizardHost.SetNextEnabled(false);
            WizardHost.SetBackEnabled(false);
            WizardHost.SetCancelEnabled(false);

            IntPtr hWnd = this.Handle;

            uint result = NativeMethods.MsiSetInternalUI(
                NativeConstants.INSTALLUILEVEL_BASIC | NativeConstants.INSTALLUILEVEL_HIDECANCEL,
                ref hWnd);

            // value of result is discarded

            string ourDir = PdnInfo.GetApplicationDir();
            string originalPackagePath = Path.Combine(ourDir, msiName);
            string targetDir           = WizardHost.GetMsiProperty(PropertyNames.TargetDir, null);
            string stagingDir          = Path.Combine(targetDir, stagingDirName);

            // The 'old' target dir is read from the registry.
            // This way if they are reinstalling to a new directory, we will propertly uninstall and cleanup
            // from the old directory.
            // The 'old' target dir defaults to the 'new' target dir (in case of new installation)
            string oldTargetDir  = WizardHost.GetMsiProperty(PropertyNames.TargetDir, targetDir, true);
            string oldStagingDir = Path.Combine(oldTargetDir, stagingDirName);

            // Uninstallers should skip certain parts of cleanup when we're going to turn around
            // and install a newer version right away
            WizardHost.SetMsiProperty(PropertyNames.SkipCleanup, "0");

            // Uninstall anything already in the staging directory (should only be the previous version)
            if (Directory.Exists(oldStagingDir))
            {
                this.infoText.Text = this.uninstallingText;
                WizardHost.SetMsiProperty(PropertyNames.SkipCleanup, "1");

                foreach (string filePath in Directory.GetFiles(oldStagingDir, "*.msi"))
                {
                    uint result2 = NativeMethods.MsiInstallProduct(
                        filePath,
                        "REMOVE=ALL " +
                        PropertyNames.SkipCleanup + "=1 " +
                        PropertyNames.DesktopShortcut + "=" + WizardHost.GetMsiProperty(PropertyNames.DesktopShortcut, "1"));
                }
            }

            // Proceed with installation
            this.infoText.Text = this.installingText;

            Directory.CreateDirectory(stagingDir);
            string msiPath        = Path.Combine(stagingDir, msiName);
            string dstPackagePath = GetOriginalMsiName(msiPath);

            // Copy the MSI to the Staging directory before installing. This way it will always
            // be available when Windows Installer needs to refer to it.
            FileInfo info = new FileInfo(originalPackagePath);

            info.CopyTo(dstPackagePath, true);

            // Keep an open file handle so that setupngen.exe cannot delete the file.
            // This happens if the current installation of Paint.NET

            // We need to set the Target Platform property of the MSI before we install it.
            // This way if the user types "C:\Program Files\Whatever" on an x64 system, it will
            // not get redirected over to "C:\Program Files (x86)\Whatever"
            Msi.SetMsiTargetPlatform(dstPackagePath, PaintDotNet.SystemLayer.Processor.NativeArchitecture);

            string commandLine1 = WizardHost.GetMsiCommandLine();
            string commandLine  = commandLine1;

            if (commandLine.Length > 0)
            {
                commandLine += " ";
            }

            commandLine += PropertyNames.QueueNgen + "=1";

            // Install newest package
            result = NativeMethods.MsiInstallProduct(dstPackagePath, commandLine);

            if (result == NativeConstants.ERROR_SUCCESS ||
                result == NativeConstants.ERROR_SUCCESS_REBOOT_INITIATED ||
                result == NativeConstants.ERROR_SUCCESS_REBOOT_REQUIRED)
            {
                ShowBanners();

                WizardHost.SaveMsiProperties();

                // clean up staging dir
                string msiFileName = Path.GetFileName(dstPackagePath);
                foreach (string filePath in Directory.GetFiles(stagingDir, "*.msi"))
                {
                    string fileName = Path.GetFileName(filePath);

                    if (0 != string.Compare(msiFileName, fileName, true, CultureInfo.InvariantCulture))
                    {
                        File.Delete(filePath);
                    }
                }

                // Run "ngen.exe executeQueuedItems", aka "Optimizing performance for your system..."
                if (Application.VisualStyleState == VisualStyleState.ClientAreaEnabled ||
                    Application.VisualStyleState == VisualStyleState.ClientAndNonClientAreasEnabled)
                {
                    this.progressBar.Style   = ProgressBarStyle.Marquee;
                    this.progressBar.Visible = true;
                }

                string       ngenExe = PdnInfo.GetNgenPath();
                const string ngenArg = "executeQueuedItems";

                try
                {
                    this.infoText.Text = this.optimizingText;
                    ProcessStartInfo psi = new ProcessStartInfo(ngenExe, ngenArg);
                    psi.UseShellExecute = false;
                    psi.CreateNoWindow  = true;
                    Process process = Process.Start(psi);

                    while (!process.HasExited)
                    {
                        System.Threading.Thread.Sleep(10);
                        Application.DoEvents();
                    }
                }

                catch
                {
                    // If this fails, do not fail the installation
                }

                // Try to write locale setting to registry
                try
                {
                    Settings.SystemWide.SetString("LanguageName", CultureInfo.CurrentUICulture.Name);
                }

                catch (Exception)
                {
                    // Ignore errors, however
                }

                SystemSounds.Beep.Play();

                WizardHost.SetFinished(true);
                this.progressBar.Visible = false;

                // set text to indicate success
                WizardHost.HeaderText = PdnResources.GetString("SetupWizard.InstallingPage.HeaderText.Success");
                string infoFormat;

                if (result == NativeConstants.ERROR_SUCCESS)
                {
                    WizardHost.RebootRequired = false;
                    infoFormat = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Success.Format");
                }
                else
                {
                    WizardHost.RebootRequired = true;
                    infoFormat = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Success.RebootRequired.Format");
                }

                this.infoText.Text = string.Format(infoFormat, this.appName);
                WizardHost.SetBackEnabled(false);
            }
            else
            {
                WizardHost.SetFinished(true);
                this.progressBar.Visible = false;

                // set text to indicate failure
                WizardHost.HeaderText = PdnResources.GetString("SetupWizard.InstallingPage.HeaderText.Failure");
                string infoFormat  = PdnResources.GetString("SetupWizard.InstallingPage.InfoText.Text.Failure.Format");
                string errorString = NativeMethods.FormatMessageW(result);
                this.errorLabel.Font    = WizardHost.NormalTextFont;
                this.errorLabel.Visible = true;
                this.errorLabel.Text    = errorString;
                this.infoText.Text      = string.Format(infoFormat, this.appName) + " (" + result.ToString() + ")";
                WizardHost.SetBackEnabled(false);
            }
        }
Example #10
0
 private void OnMenuHelpForumClick(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(base.AppWorkspace, "/redirect/forum_hm.html");
 }
Example #11
0
 private void OnMenuHelpPdnSearchEngineClick(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(base.AppWorkspace, "/redirect/search_hm.html");
 }
Example #12
0
 private void OnMenuHelpTutorialsClick(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(base.AppWorkspace, "/redirect/tutorials_hm.html");
 }
Example #13
0
        /// <summary>
        /// Pastes from the clipboard into the document.
        /// </summary>
        /// <returns>true if the paste operation completed, false if there was an error or if it was cancelled for some reason</returns>
        public bool PerformAction()
        {
            SurfaceForClipboard surfaceForClipboard = null;
            IDataObject         clipData            = null;

            try
            {
                Utility.GCFullCollect();
                clipData = Clipboard.GetDataObject();
            }

            catch (ExternalException)
            {
                Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.TransferFromClipboard"));
                return(false);
            }

            catch (OutOfMemoryException)
            {
                Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.OutOfMemory"));
                return(false);
            }

            // First "ask" the current tool if it wants to handle it
            bool handledByTool = false;

            if (this.documentWorkspace.Tool != null)
            {
                this.documentWorkspace.Tool.PerformPaste(clipData, out handledByTool);
            }

            if (handledByTool)
            {
                return(true);
            }

            if (clipData.GetDataPresent(typeof(SurfaceForClipboard)))
            {
                try
                {
                    Utility.GCFullCollect();
                    surfaceForClipboard = clipData.GetData(typeof(SurfaceForClipboard)) as SurfaceForClipboard;
                }

                catch (OutOfMemoryException)
                {
                    Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.OutOfMemory"));
                    return(false);
                }
            }

            if (surfaceForClipboard != null && surfaceForClipboard.MaskedSurface.IsDisposed)
            {
                // Have been getting crash reports where sfc contains a disposed MaskedSurface ...
                surfaceForClipboard = null;
            }

            if (surfaceForClipboard == null &&
                clipData.GetDataPresent(DataFormats.Bitmap))
            {
                Image image;

                try
                {
                    Utility.GCFullCollect();
                    image = (Image)clipData.GetData(DataFormats.Bitmap);
                }

                catch (OutOfMemoryException)
                {
                    Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.OutOfMemory"));
                    return(false);
                }

                // Sometimes we get weird errors if we're in, say, 16-bit mode but the image was copied
                // to the clipboard in 32-bit mode
                if (image == null)
                {
                    Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.NotRecognized"));
                    return(false);
                }

                MaskedSurface maskedSurface = null;

                try
                {
                    Utility.GCFullCollect();
                    Bitmap  bitmap;
                    Surface surface = null;

                    if (image is Bitmap)
                    {
                        bitmap = (Bitmap)image;
                        image  = null;
                    }
                    else
                    {
                        bitmap = new Bitmap(image);
                        image.Dispose();
                    }

                    surface = Surface.CopyFromBitmap(bitmap);
                    bitmap.Dispose();
                    bitmap = null;

                    maskedSurface = new MaskedSurface(surface, new PdnRegion(surface.Bounds));

                    surface.Dispose();
                    surface = null;
                }

                catch (Exception)
                {
                    Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.OutOfMemory"));
                    return(false);
                }

                surfaceForClipboard = new SurfaceForClipboard(maskedSurface);
            }

            if (surfaceForClipboard == null || surfaceForClipboard.MaskedSurface == null)
            {
                // silently fail: like what if a program overwrote the clipboard in between the time
                // we enabled the "Paste" menu item and the user actually clicked paste?
                // it could happen!
                Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("PasteAction.Error.NoImage"));
                return(false);
            }

            // If the image is larger than the document, ask them if they'd like to make the image larger first
            Rectangle bounds = surfaceForClipboard.Bounds;

            if (bounds.Width > this.documentWorkspace.Document.Width ||
                bounds.Height > this.documentWorkspace.Document.Height)
            {
                DialogResult dr = MessageBox.Show(
                    this.documentWorkspace,
                    PdnResources.GetString("PasteAction.Question.ExpandCanvas"),
                    PdnInfo.GetAppName(),
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Question);

                int layerIndex = this.documentWorkspace.ActiveLayerIndex;

                switch (dr)
                {
                case DialogResult.Yes:
                    Size newSize = new Size(Math.Max(bounds.Width, this.documentWorkspace.Document.Width),
                                            Math.Max(bounds.Height, this.documentWorkspace.Document.Height));

                    Document newDoc = CanvasSizeAction.ResizeDocument(
                        this.documentWorkspace.Document,
                        newSize,
                        AnchorEdge.TopLeft,
                        this.documentWorkspace.AppWorkspace.AppEnvironment.SecondaryColor);

                    if (newDoc == null)
                    {
                        return(false);    // user clicked cancel!
                    }
                    else
                    {
                        HistoryMemento rdha = new ReplaceDocumentHistoryMemento(
                            CanvasSizeAction.StaticName,
                            CanvasSizeAction.StaticImage,
                            this.documentWorkspace);

                        this.documentWorkspace.Document = newDoc;
                        this.documentWorkspace.History.PushNewMemento(rdha);
                        this.documentWorkspace.ActiveLayer = (Layer)this.documentWorkspace.Document.Layers[layerIndex];
                    }

                    break;

                case DialogResult.No:
                    break;

                case DialogResult.Cancel:
                    return(false);

                default:
                    throw new InvalidEnumArgumentException("Internal error: DialogResult was neither Yes, No, nor Cancel");
                }
            }

            // Decide where to paste to: If the paste is within bounds of the document, do as normal
            // Otherwise, center it.
            Rectangle docBounds  = this.documentWorkspace.Document.Bounds;
            Rectangle intersect1 = Rectangle.Intersect(docBounds, bounds);
            bool      doMove     = intersect1 != bounds; //intersect1.IsEmpty;

            Point pasteOffset;

            if (doMove)
            {
                pasteOffset = new Point(-bounds.X + (docBounds.Width / 2) - (bounds.Width / 2),
                                        -bounds.Y + (docBounds.Height / 2) - (bounds.Height / 2));
            }
            else
            {
                pasteOffset = new Point(0, 0);
            }

            // Paste to the place it was originally copied from (for PDN-to-PDN transfers)
            // and then if its not pasted within the viewable rectangle we pan to that location
            RectangleF visibleDocRectF = this.documentWorkspace.VisibleDocumentRectangleF;
            Rectangle  visibleDocRect  = Utility.RoundRectangle(visibleDocRectF);
            Rectangle  bounds2         = new Rectangle(new Point(bounds.X + pasteOffset.X, bounds.Y + pasteOffset.Y), bounds.Size);
            Rectangle  intersect2      = Rectangle.Intersect(bounds2, visibleDocRect);
            bool       doPan           = intersect2.IsEmpty;

            this.documentWorkspace.SetTool(null);
            this.documentWorkspace.SetToolFromType(typeof(MoveTool));

            ((MoveTool)this.documentWorkspace.Tool).PasteMouseDown(surfaceForClipboard, pasteOffset);

            if (doPan)
            {
                Point centerPtView = new Point(visibleDocRect.Left + (visibleDocRect.Width / 2),
                                               visibleDocRect.Top + (visibleDocRect.Height / 2));

                Point centerPtPasted = new Point(bounds2.Left + (bounds2.Width / 2),
                                                 bounds2.Top + (bounds2.Height / 2));

                Size delta = new Size(centerPtPasted.X - centerPtView.X,
                                      centerPtPasted.Y - centerPtView.Y);

                PointF docScrollPos = this.documentWorkspace.DocumentScrollPositionF;

                PointF newDocScrollPos = new PointF(docScrollPos.X + delta.Width,
                                                    docScrollPos.Y + delta.Height);

                this.documentWorkspace.DocumentScrollPositionF = newDocScrollPos;
            }

            return(true);
        }
Example #14
0
 private void MoreInfoLink_Click(object sender, EventArgs e)
 {
     PdnInfo.OpenUrl(this, this.moreInfoTarget.ToString());
 }
Example #15
0
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "/proc":
                    if (i + 1 == args.Length)
                    {
                        Console.WriteLine("Use /proc <N> to specify number of processors");
                        return;
                    }

                    int numProcs;

                    if (Int32.TryParse(args[i + 1], out numProcs))
                    {
                        // only increment i if successful b/c we're going to continue the run
                        // with the default # of processors and don't want to automatically
                        // eat the next parameter.
                        ++i;
                        Processor.LogicalCpuCount = numProcs;
                    }
                    else
                    {
                        Console.WriteLine("You must specify a integer for /proc <N>, continuing with default");
                    }
                    break;

                case "/image":
                    if (i + 1 == args.Length)
                    {
                        Console.WriteLine("Use /image <filename> to specify a file to perform benchmark with");
                        return;
                    }

                    ++i;
                    benchmarkImageName = args[i];

                    if (!System.IO.File.Exists(benchmarkImageName))
                    {
                        Console.WriteLine("Specified image doesn't exist");
                        return;
                    }
                    break;

                case "/tsv":
                    useTsvOutput = true;
                    break;

                case "/?":
                    PrintHelp();
                    return;

                default:
                    break;
                }
            }

            //Processor.LogicalCpuCount = 1;
            Console.WriteLine("PdnBench v" + PdnInfo.GetVersion());
            Console.WriteLine("Running in " + (8 * Marshal.SizeOf(typeof(IntPtr))) + "-bit mode on " +
                              Processor.NativeArchitecture.ToString().ToLower() + " OS");
            Console.WriteLine("Processor: " + Processor.LogicalCpuCount + "x " + Processor.CpuName);
            Console.WriteLine("Memory: " + ((Memory.TotalPhysicalBytes / 1024) / 1024) + " MB");
            Console.WriteLine();

            Console.WriteLine("Using " + Processor.LogicalCpuCount + " threads.");

            ArrayList benchmarks = new ArrayList();

            Document document;

            Console.Write("Loading image ... ");

            Stream imageStream = null;

            try
            {
                imageStream = (defaultImageName == benchmarkImageName) ?
                              Assembly.GetExecutingAssembly().GetManifestResourceStream(benchmarkImageName) :
                              new FileStream(benchmarkImageName, FileMode.Open);

                JpegFileType jft = new JpegFileType();
                document = jft.Load(imageStream);
            }

            finally
            {
                if (imageStream != null)
                {
                    imageStream.Dispose();
                }
            }

            Console.WriteLine("(" + document.Width + " x " + document.Height + ") done");

            Surface surface = ((BitmapLayer)document.Layers[0]).Surface;

#if EFFECTS
            for (double i = 0; i < (2 * Math.PI); i += 70.0 * ((2 * Math.PI) / 360.0))
            {
                benchmarks.Add(
                    new EffectBenchmark("Rotate/Zoom at " + ((i * 180.0) / Math.PI).ToString("F2") + " degrees",
                                        3,
                                        new PaintDotNet.Effects.RotateZoomEffect(),
                                        new PaintDotNet.Effects.RotateZoomEffectConfigToken(
                                            true,
                                            (float)(Math.PI * 0.3f),
                                            (float)((Math.PI * -0.4) + i),
                                            50,
                                            0.5f,
                                            new PointF(-0.2f, 0.3f),
                                            false,
                                            true),
                                        surface));
            }

            for (int i = 1; i <= 4; i += 3)
            {
                for (int j = 10; j < 100; j += 75)
                {
                    benchmarks.Add(
                        new EffectBenchmark(
                            "Oil Painting, brush size = " + i + ", coarseness = " + j,
                            1,
                            new OilPaintingEffect(),
                            new TwoAmountsConfigToken(i, j),
                            surface));
                }
            }

            for (int i = 2; i <= 50; i += i)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Blur with radius of " + i,
                        1,
                        new BlurEffect(),
                        new AmountEffectConfigToken(i),
                        surface));
            }

            for (int i = 1; i <= 4; i += 3)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Sharpen with value of " + i,
                        1,
                        new SharpenEffect(),
                        new AmountEffectConfigToken(i),
                        surface));
            }

            benchmarks.Add(
                new EffectBenchmark(
                    "Auto-Levels",
                    50,
                    new AutoLevelEffect(),
                    null,
                    surface));

            for (int i = 81; i >= 5; i /= 3)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Clouds, roughness = " + i,
                        2,
                        new CloudsEffect(),
                        new CloudsEffectConfigToken(50, i, 12345, new UserBlendOps.NormalBlendOp()),
                        surface));
            }

            for (int i = 4; i <= 64; i *= 4)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Median, radius " + i,
                        1,
                        new MedianEffect(),
                        new TwoAmountsConfigToken(/*radius*/ i, /*roughness*/ 50),
                        surface));
            }

            for (int i = 4; i <= 64; i *= 4)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Unfocus, radius " + i,
                        1,
                        new UnfocusEffect(),
                        new AmountEffectConfigToken(i),
                        surface));
            }

            benchmarks.Add(
                new EffectBenchmark(
                    "Motion Blur, Horizontal",
                    1,
                    new MotionBlurEffect(),
                    new MotionBlurEffectConfigToken(0, 100, true),
                    surface));

            benchmarks.Add(
                new EffectBenchmark(
                    "Motion Blur, Vertical",
                    1,
                    new MotionBlurEffect(),
                    new MotionBlurEffectConfigToken(90, 100, true),
                    surface));
#endif

            Surface dst = new Surface(surface.Width * 4, surface.Height * 4);

#if RESIZE
            // Resize benchmarks
            for (int i = 1; i < 8; i += 2)
            {
                int newWidth  = i * (dst.Width / 8);
                int newHeight = i * (dst.Height / 8);

                Surface dstWindow = dst.CreateWindow(new Rectangle(0, 0, newWidth, newHeight));
                benchmarks.Add(new ResizeBenchmark("Resize from " + surface.Width + "x" + surface.Height + " to " + newWidth + "x" + newHeight, surface, dstWindow));
                benchmarks.Add(new ResizeBenchmark("Resize from " + newWidth + "x" + newHeight + " to " + surface.Width + "x" + surface.Height, dstWindow, surface));
            }
#endif

#if GRADIENT
            // Gradient benchmarks
            benchmarks.Add(new GradientBenchmark(
                               "Linear reflected gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                               dst,
                               new GradientRenderers.LinearReflected(false, new UserBlendOps.NormalBlendOp()),
                               2));

            benchmarks.Add(new GradientBenchmark(
                               "Conical gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                               dst,
                               new GradientRenderers.Conical(false, new UserBlendOps.NormalBlendOp()),
                               2));

            benchmarks.Add(new GradientBenchmark(
                               "Radial gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                               dst,
                               new GradientRenderers.Radial(false, new UserBlendOps.NormalBlendOp()),
                               2));
#endif

#if COMPOSITION
            // Composition benchmarks
            Document    doc1   = new Document(surface.Size);
            BitmapLayer layer1 = Layer.CreateBackgroundLayer(doc1.Width, doc1.Height);
            layer1.Surface.CopySurface(surface);
            doc1.Layers.Add(layer1);
            doc1.Layers.Add(layer1.Clone());
            doc1.Layers.Add(layer1.Clone());
            doc1.Layers.Add(layer1.Clone());

            benchmarks.Add(new CompositionBenchmark("Compositing one layer, Normal blend mode, 255 opacity (" + CompositionBenchmark.Iterations + "x)",
                                                    doc1,
                                                    surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                if (layerIndex == 0)
                {
                    layer.Visible = true;
                    layer.Opacity = 255;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }
                else
                {
                    layer.Visible = false;
                }
            }));

            benchmarks.Add(new CompositionBenchmark("Compositing one layer, Normal blend mode, 128 opacity (" + CompositionBenchmark.Iterations + "x)",
                                                    doc1,
                                                    surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                if (layerIndex == 0)
                {
                    layer.Visible = true;
                    layer.Opacity = 128;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }
                else
                {
                    layer.Visible = false;
                }
            }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 255 opacity (" + CompositionBenchmark.Iterations + "x)",
                                                    doc1,
                                                    surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                layer.Visible = true;
                layer.Opacity = 255;
                ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
            }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 255 (layer 0) and 128 (layer 1-3) opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                layer.Visible = true;
                layer.Opacity = 128;
                ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
            }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 128 opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                layer.Visible = true;
                layer.Opacity = 128;
                ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
            }));

            benchmarks.Add(new CompositionBenchmark("Compositing three layers, Normal+Multiply+Overlay blending, 150+255+170 opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                                                    delegate(int layerIndex, Layer layer)
            {
                if (layerIndex == 0)
                {
                    layer.Visible = true;
                    layer.Opacity = 150;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }
                else if (layerIndex == 1)
                {
                    layer.Visible = true;
                    layer.Opacity = 255;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.MultiplyBlendOp());
                }
                else if (layerIndex == 2)
                {
                    layer.Visible = true;
                    layer.Opacity = 170;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.OverlayBlendOp());
                }
                else
                {
                    layer.Visible = false;
                }
            }));
#endif

#if TRANSFORM
            // Transform benchmarks
            Matrix m = new Matrix();
            m.Reset();

            MaskedSurface msSimple = new MaskedSurface(surface, new PdnRegion(surface.Bounds)); // simple masked surface

            PdnRegion complexRegion = new PdnRegion(surface.Bounds);

            // cut 4 holes in region 1 to form a complex clipping surface
            for (int x = -1; x < 3; ++x)
            {
                for (int y = -1; y < 3; ++y)
                {
                    int left   = (1 + (x * 3)) * (surface.Width / 6);
                    int top    = (1 + (x * 3)) * (surface.Height / 6);
                    int right  = (2 + (x * 3)) * (surface.Width / 6);
                    int bottom = (2 + (x * 3)) * (surface.Height / 6);

                    Rectangle       rect = Rectangle.FromLTRB(left, top, right, bottom);
                    PdnGraphicsPath path = new PdnGraphicsPath();
                    path.AddEllipse(rect);
                    complexRegion.Exclude(path);
                }
            }

            MaskedSurface msComplex = new MaskedSurface(surface, complexRegion);

            benchmarks.Add(new TransformBenchmark("Transform simple surface, no transform, nearest neighbor resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m,
                                                  false));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, no transform, nearest neighbor resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m,
                                                  false));

            benchmarks.Add(new TransformBenchmark("Transform simple surface, no transform, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m,
                                                  true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, no transform, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m,
                                                  true));

            Matrix m2 = m.Clone();
            m2.RotateAt(45.0f, new PointF(surface.Width / 2, surface.Height / 2));

            benchmarks.Add(new TransformBenchmark("Transform simple surface, 45 deg. rotation about center, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m2,
                                                  true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, 45 deg. rotation about center, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m2,
                                                  true));

            Matrix m3 = m.Clone();
            m3.Scale(0.5f, 0.75f);

            benchmarks.Add(new TransformBenchmark("Transform simple surface, 50% x-scaling 75% y-scaling, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m3,
                                                  true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, 50% x-scaling 75% y-scaling, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                                                  surface,
                                                  msSimple,
                                                  m3,
                                                  true));
#endif

#if BLIT
            // Blit benchmarks
            benchmarks.Add(new ZoomOutBlitBenchmark("Zoom out, rotated grid multisampling, 66% (" + ZoomOutBlitBenchmark.IterationCount + "x)",
                                                    surface,
                                                    dst,
                                                    new Size((surface.Width * 2) / 3, (surface.Height * 2) / 3)));

            benchmarks.Add(new ZoomOutBlitBenchmark("Zoom out, rotated grid multisampling, 28% (" + ZoomOutBlitBenchmark.IterationCount + "x)",
                                                    surface,
                                                    dst,
                                                    new Size((surface.Width * 28) / 100, (surface.Height * 28) / 100)));

            benchmarks.Add(new ZoomOneToOneBlitBenchmark("Zoom 1:1, straight blit (" + ZoomOneToOneBlitBenchmark.IterationCount + "x)",
                                                         surface,
                                                         dst.CreateWindow(new Rectangle(0, 0, surface.Width, surface.Height))));
#endif

            // Run benchmarks!
            Timing timing = new Timing();
            ulong  start  = timing.GetTickCount();

            foreach (Benchmark benchmark in benchmarks)
            {
                Console.Write(benchmark.Name + (useTsvOutput ? "\t" : " ... "));
                TimeSpan timeSpan = benchmark.Execute();
                Console.WriteLine(" " + timeSpan.TotalMilliseconds.ToString() + (useTsvOutput ? "\t" : "") + " milliseconds");

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            ulong end = timing.GetTickCount();

            Console.WriteLine();
            Console.WriteLine("Total time: " + (useTsvOutput ? "\t" : "") + (end - start).ToString() + (useTsvOutput ? "\t" : "") + " milliseconds");
            Console.WriteLine();
        }
Example #16
0
        static void MainImpl(string[] args)
        {
            if (!PdnInfo.HandleExpiration(null))
            {
                return;
            }

            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
            UI.EnableDpiAware();

            // Uncomment to test German
            //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de");

            bool doInstall        = true;
            bool doMsiDump        = false;
            bool restartPdnOnExit = false;

            string[] propertyDefaults = PropertyNames.Defaults;

            SetupWizard setupWizard = new SetupWizard();

            // Parse through command-line options
            for (int i = 0; i < args.Length; ++i)
            {
                string arg      = args[i];
                string argLower = arg.ToLower();

                switch (argLower)
                {
                case "-?":
                case "/?":
                case "-help":
                case "/help":
                    ShowHelp();
                    doInstall = false;
                    break;

                case "-restartpdnonexit":
                case "/restartpdnonexit":
                    restartPdnOnExit = true;
                    break;

                case "-skipconfig":
                case "/skipconfig":
                    KillParentPdnExe();
                    setupWizard.SkipConfig = true;
                    setupWizard.SetMsiProperty(PropertyNames.PdnUpdating, "1");
                    break;

                case "-auto":
                case "/auto":
                    setupWizard.AutoMode   = true;
                    setupWizard.SkipConfig = true;
                    break;

                case "-createmsi":
                case "/createmsi":
                    doMsiDump        = true;
                    propertyDefaults = PropertyNames.AdGpoDefaults;
                    break;

                default:
                    setupWizard.AddPropertyFromArg(arg);
                    break;
                }
            }

            // Load all the propreties that we always need to have. Defaults will be loaded
            // for properties that are not already set.
            for (int i = 0; i < propertyDefaults.Length; i += 2)
            {
                setupWizard.GetMsiProperty(propertyDefaults[i], propertyDefaults[i + 1]);
            }

            setupWizard.SetMsiProperty(PropertyNames.PdnUpdating, "0");

            // Only allow 1 instance of setup wizard running at a time...
            bool  createdNew;
            Mutex mutex = new Mutex(false, mutexName, out createdNew);

            doInstall &= createdNew;

            if (doInstall)
            {
                if (CheckRequirements())
                {
                    if (doMsiDump)
                    {
                        setupWizard.ClearPageStack();
                        setupWizard.GoToPage(typeof(CreateMsiPage));
                    }

                    setupWizard.ShowDialog();
                }

                // When we do an update, Mono Paint launches our installer with the /restartPdnOnExit
                // flag. This tells us to run Mono Paint when the update is finished. This accomplishes
                // two things:
                //
                // 1. Adds a slight amount of continuity for the user. When they're installing an update
                //    they'll probably want to start-up Mono Paint right away. So we do it for them.
                // 2. Cleans up (deletes) the downloaded setup file. Otherwise, the user has to make sure
                //    that they immediately re-run Mono Paint under the same user account in order to
                //    clean this up.
                //
                // #2 does introduce a slight race condition, so PaintDotNet.exe will actually retry
                // up to 3 times to delete the file with a 1 second pause between retries. This should
                // give enough time for the setup processes to unwind without causing too horrible of
                // a delay in the worst case.
                if (restartPdnOnExit && !setupWizard.RebootRequired)
                {
                    string targetDir = setupWizard.GetMsiProperty(PropertyNames.TargetDir, null);

                    if (targetDir != null)
                    {
                        string pdnPathName = Path.Combine(targetDir, "PaintDotNet.exe");

                        if (File.Exists(pdnPathName))
                        {
                            Process.Start(pdnPathName);
                        }
                    }
                }

                setupWizard.Dispose();
            }

            mutex.Close();
        }
Example #17
0
 private void MenuHelpPdnSearchEngine_Click(object sender, EventArgs e)
 {
     PdnInfo.LaunchWebSite(AppWorkspace, InvariantStrings.SearchEngineHelpMenu);
 }