<commit_before>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using RawParser.View.Exception;
using Windows.Storage.Provider;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using System.Runtime.InteropServices;
using RawParser.View.UIHelper;
using RawParser.Image;
using RawParser.Parser;
using RawParser.Effect;
using RawParser.Model.Settings;
using RawParser.Model.Encoder;

namespace RawParser
{
    [ComImport]
    [Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    unsafe interface IMemoryBufferByteAccess
    {
        void GetBuffer(out byte* buffer, out uint capacity);
    }
    /// <summary>
    /// The main class of the appliation
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public RawImage raw;
        public bool imageSelected { set; get; }
        public double pageWidth;
        public double pageHeight;
        private int currentImageDisplayedHeight;
        private int currentImageDisplayedWidth;

        bool cameraWB = true;
        private bool ExposuredragStarted;
        private bool WBdragStarted;

        public MainPage()
        {
            InitializeComponent();
            SettingStorage.init();
            NavigationCacheMode = NavigationCacheMode.Enabled;
            imageSelected = false;

        }

        private async void appBarImageChooseClick(object sender, RoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker();
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            filePicker.FileTypeFilter.Add(".nef");
            filePicker.FileTypeFilter.Add(".tiff");
            filePicker.FileTypeFilter.Add(".dng");
            StorageFile file = await filePicker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                try
                {
                    OpenFile(file);
                }
                catch (Exception ex)
                {
                    ExceptionDisplay.display(ex.Message + ex.StackTrace);
                }
            }
            else
            {
                //TODO
            }
        }

        //Always call in the UI thread
        private async void emptyImage()
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher
                    .RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        //empty the previous image data
                        raw = null;
                        //empty the image display
                        imageBox.Source = null;
                        imageBox.UpdateLayout();
                        //empty the exif data
                        exifDisplay.ItemsSource = null;
                        //empty the histogram
                        enableEditingControl(false);
                    });
        }

        private async void enableEditingControl(bool v)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher
                 .RunAsync(CoreDispatcherPriority.Normal, () =>
                 {
                     colorTempSlider.IsEnabled = v;
                     exposureSlider.IsEnabled = v;
                     gammaSlider.IsEnabled = v;
                     //contrastSlider.IsEnabled = v;
                     brightnessSlider.IsEnabled = v;
                 });
        }

        /*
         * For the zoom of the image
         * 
         */

        private void PageSizeChanged(object sender, SizeChangedEventArgs e)
        {
            pageWidth = e.NewSize.Width;
            pageHeight = e.NewSize.Height;
            setScrollProperty();
        }

        private void OpenFile(StorageFile file)
        {
            //Open the file with the correct parser
            AParser parser;
            switch (file.FileType.ToUpper())
            {
                case ".NEF":
                    parser = new NEFParser();
                    break;
                case ".DNG":
                    parser = new DNGParser();
                    break;
                case ".TIFF":
                    parser = new DNGParser();
                    break;
                default:
                    throw new System.Exception("File not supported"); //todo change exception types
            }

            //Add a loading screen
            progressDisplay.Visibility = Visibility.Visible;
            histoLoadingBar.Visibility = Visibility.Visible;
            emptyImage();

            Task t = Task.Run(async () =>
            {
                using (Stream stream = (await file.OpenReadAsync()).AsStreamForRead())
                {
                    raw = new RawImage();
                    raw.fileName = file.DisplayName;

                    //Set the stream
                    parser.setStream(stream);

                    //read the thumbnail
                    raw.thumbnail = parser.parseThumbnail();
                    displayImage(JpegHelper.getJpegInArray(raw.thumbnail));

                    //read the preview
                    parser.parsePreview();
                    //displayImage(RawImage.getImageAsBitmap(parser.parsePreview()));

                    //read the exifi
                    raw.exif = parser.parseExif();
                    displayExif();
                    //read the data 
                    raw.height = parser.height;
                    raw.width = parser.width;
                    raw.colorDepth = parser.colorDepth;
                    raw.cfa = parser.cfa;
                    raw.camMul = parser.camMul;
                    raw.rawData = parser.parseRAWImage();
                    raw.camMul = parser.camMul;

                    Demosaic.demos(ref raw, demosAlgorithm.NearNeighbour);

                    //activate the editing control
                    enableEditingControl(true);

                    //create a small image from raw to display
                    bool autoFactor = SettingStorage.autoPreviewFactor;
                    int previewFactor = 0;
                    if (autoFactor)
                    {
                        if (raw.height > raw.width)
                        {
                            previewFactor = (int)(raw.height / 720);
                        }
                        else
                        {
                            previewFactor = (int)(raw.width / 1080);
                        }
                        int start = 1;
                        for (; previewFactor > (start << 1); start <<= 1) ;
                        if ((previewFactor - start) < ((start << 1) - previewFactor)) previewFactor = start;
                        else previewFactor <<= 1;
                    }
                    else
                    {
                        previewFactor = SettingStorage.previewFactor;
                    }
                    raw.previewHeight = (uint)(raw.height / previewFactor);
                    raw.previewWidth = (uint)(raw.width / previewFactor);
                    raw.previewData = new ushort[raw.previewHeight * raw.previewWidth * 3];
                    for (int i = 0; i < raw.previewHeight; i++)
                    {
                        for (int j = 0; j < raw.previewWidth; j++)
                        {
                            raw.previewData[((i * raw.previewWidth) + j) * 3] = raw.rawData[((i * previewFactor * raw.previewWidth) + j) * 3 * previewFactor];
                            raw.previewData[(((i * raw.previewWidth) + j) * 3) + 1] = raw.rawData[(((i * previewFactor * raw.previewWidth) + j) * 3 * previewFactor) + 1];<commit_msg>Reduced size of auto preview (should be changed depending on devicefamily)<commit_after>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using RawParser.View.Exception;
using Windows.Storage.Provider;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using System.Runtime.InteropServices;
using RawParser.View.UIHelper;
using RawParser.Image;
using RawParser.Parser;
using RawParser.Effect;
using RawParser.Model.Settings;
using RawParser.Model.Encoder;

namespace RawParser
{
    [ComImport]
    [Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    unsafe interface IMemoryBufferByteAccess
    {
        void GetBuffer(out byte* buffer, out uint capacity);
    }
    /// <summary>
    /// The main class of the appliation
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public RawImage raw;
        public bool imageSelected { set; get; }
        public double pageWidth;
        public double pageHeight;
        private int currentImageDisplayedHeight;
        private int currentImageDisplayedWidth;

        bool cameraWB = true;
        private bool ExposuredragStarted;
        private bool WBdragStarted;

        public MainPage()
        {
            InitializeComponent();
            SettingStorage.init();
            NavigationCacheMode = NavigationCacheMode.Enabled;
            imageSelected = false;

        }

        private async void appBarImageChooseClick(object sender, RoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker();
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            filePicker.FileTypeFilter.Add(".nef");
            filePicker.FileTypeFilter.Add(".tiff");
            filePicker.FileTypeFilter.Add(".dng");
            StorageFile file = await filePicker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                try
                {
                    OpenFile(file);
                }
                catch (Exception ex)
                {
                    ExceptionDisplay.display(ex.Message + ex.StackTrace);
                }
            }
            else
            {
                //TODO
            }
        }

        //Always call in the UI thread
        private async void emptyImage()
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher
                    .RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        //empty the previous image data
                        raw = null;
                        //empty the image display
                        imageBox.Source = null;
                        imageBox.UpdateLayout();
                        //empty the exif data
                        exifDisplay.ItemsSource = null;
                        //empty the histogram
                        enableEditingControl(false);
                    });
        }

        private async void enableEditingControl(bool v)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher
                 .RunAsync(CoreDispatcherPriority.Normal, () =>
                 {
                     colorTempSlider.IsEnabled = v;
                     exposureSlider.IsEnabled = v;
                     gammaSlider.IsEnabled = v;
                     //contrastSlider.IsEnabled = v;
                     brightnessSlider.IsEnabled = v;
                 });
        }

        /*
         * For the zoom of the image
         * 
         */

        private void PageSizeChanged(object sender, SizeChangedEventArgs e)
        {
            pageWidth = e.NewSize.Width;
            pageHeight = e.NewSize.Height;
            setScrollProperty();
        }

        private void OpenFile(StorageFile file)
        {
            //Open the file with the correct parser
            AParser parser;
            switch (file.FileType.ToUpper())
            {
                case ".NEF":
                    parser = new NEFParser();
                    break;
                case ".DNG":
                    parser = new DNGParser();
                    break;
                case ".TIFF":
                    parser = new DNGParser();
                    break;
                default:
                    throw new System.Exception("File not supported"); //todo change exception types
            }

            //Add a loading screen
            progressDisplay.Visibility = Visibility.Visible;
            histoLoadingBar.Visibility = Visibility.Visible;
            emptyImage();

            Task t = Task.Run(async () =>
            {
                using (Stream stream = (await file.OpenReadAsync()).AsStreamForRead())
                {
                    raw = new RawImage();
                    raw.fileName = file.DisplayName;

                    //Set the stream
                    parser.setStream(stream);

                    //read the thumbnail
                    raw.thumbnail = parser.parseThumbnail();
                    displayImage(JpegHelper.getJpegInArray(raw.thumbnail));

                    //read the preview
                    parser.parsePreview();
                    //displayImage(RawImage.getImageAsBitmap(parser.parsePreview()));

                    //read the exifi
                    raw.exif = parser.parseExif();
                    displayExif();
                    //read the data 
                    raw.height = parser.height;
                    raw.width = parser.width;
                    raw.colorDepth = parser.colorDepth;
                    raw.cfa = parser.cfa;
                    raw.camMul = parser.camMul;
                    raw.rawData = parser.parseRAWImage();
                    raw.camMul = parser.camMul;

                    Demosaic.demos(ref raw, demosAlgorithm.NearNeighbour);

                    //activate the editing control
                    enableEditingControl(true);

                    //create a small image from raw to display
                    bool autoFactor = SettingStorage.autoPreviewFactor;
                    int previewFactor = 0;
                    if (autoFactor)
                    {
                        if (raw.height > raw.width)
                        {
                            previewFactor = (int)(raw.height / 480);
                        }
                        else
                        {
                            previewFactor = (int)(raw.width / 640);
                        }
                        int start = 1;
                        for (; previewFactor > (start << 1); start <<= 1) ;
                        if ((previewFactor - start) < ((start << 1) - previewFactor)) previewFactor = start;
                        else previewFactor <<= 1;
                    }
                    else
                    {
                        previewFactor = SettingStorage.previewFactor;
                    }
                    raw.previewHeight = (uint)(raw.height / previewFactor);
                    raw.previewWidth = (uint)(raw.width / previewFactor);
                    raw.previewData = new ushort[raw.previewHeight * raw.previewWidth * 3];
                    for (int i = 0; i < raw.previewHeight; i++)
                    {
                        for (int j = 0; j < raw.previewWidth; j++)
                        {
                            raw.previewData[((i * raw.previewWidth) + j) * 3] = raw.rawData[((i * previewFactor * raw.previewWidth) + j) * 3 * previewFactor];
                            raw.previewData[(((i * raw.previewWidth) + j) * 3) + 1] = raw.rawData[(((i * previewFactor * raw.previewWidth) + j) * 3 * previewFactor) + 1];
{'fraction_non_alphanumeric': 0.0838797476184585, 'fraction_numerical': 0.005010515897562786, 'mean_word_length': 1.2896190341311429, 'pattern_counts': {'":': 6, '<': 29, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6603578', 'n_tokens_mistral': 3964, 'n_tokens_neox': 3659, 'n_words': 873}