<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/transform.h"
#include "views/controls/button/image_button.h"
#include "views/controls/textfield/textfield.h"
#include "views/focus/focus_manager.h"

namespace {

const int kKeyboardHeight = 300;
const int kKeyboardSlideDuration = 500;  // In milliseconds

PropertyAccessor<bool>* GetFocusedStateAccessor() {
  static PropertyAccessor<bool> state;
  return &state;
}

bool TabContentsHasFocus(const TabContents* contents) {
  views::View* view = static_cast<TabContentsViewTouch*>(contents->view());
  return view->Contains(view->GetFocusManager()->GetFocusedView());
}

}  // namespace

// static
const char TouchBrowserFrameView::kViewClassName[] =
    "browser/ui/touch/frame/TouchBrowserFrameView";

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, public:

TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,
                                             BrowserView* browser_view)
    : OpaqueBrowserFrameView(frame, browser_view),
      keyboard_showing_(false),
      focus_listener_added_(false),
      keyboard_(NULL) {
  registrar_.Add(this,
                 NotificationType::NAV_ENTRY_COMMITTED,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::FOCUS_CHANGED_IN_PAGE,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::TAB_CONTENTS_DESTROYED,
                 NotificationService::AllSources());

  browser_view->browser()->tabstrip_model()->AddObserver(this);

  animation_.reset(new ui::SlideAnimation(this));
  animation_->SetTweenType(ui::Tween::LINEAR);
  animation_->SetSlideDuration(kKeyboardSlideDuration);
}

TouchBrowserFrameView::~TouchBrowserFrameView() {
  browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
}

std::string TouchBrowserFrameView::GetClassName() const {
  return kViewClassName;
}

void TouchBrowserFrameView::Layout() {
  OpaqueBrowserFrameView::Layout();

  if (!keyboard_)
    return;

  keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());
  gfx::Rect bounds = GetBoundsForReservedArea();
  if (animation_->is_animating() && !keyboard_showing_) {
    // The keyboard is in the process of hiding. So pretend it still has the
    // same bounds as when the keyboard is visible. But
    // |GetBoundsForReservedArea| should not take this into account so that the
    // render view gets the entire area to relayout itself.
    bounds.set_y(bounds.y() - kKeyboardHeight);
    bounds.set_height(kKeyboardHeight);
  }
  keyboard_->SetBoundsRect(bounds);
}

void TouchBrowserFrameView::FocusWillChange(views::View* focused_before,
                                            views::View* focused_now) {
  VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
  VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
  if (before != now) {
    // TODO(varunjain): support other types of keyboard.
    UpdateKeyboardAndLayout(now == GENERIC);
  }
}

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, protected:
int TouchBrowserFrameView::GetReservedHeight() const {
  return keyboard_showing_ ? kKeyboardHeight : 0;
}

void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,
                                                 View* parent,
                                                 View* child) {
  OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);
  if (!GetFocusManager())
    return;

  if (is_add && !focus_listener_added_) {
    // Add focus listener when this view is added to the hierarchy.
    GetFocusManager()->AddFocusChangeListener(this);
    focus_listener_added_ = true;
  } else if (!is_add && focus_listener_added_) {
    // Remove focus listener when this view is removed from the hierarchy.
    GetFocusManager()->RemoveFocusChangeListener(this);
    focus_listener_added_ = false;
  }
}

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, private:

void TouchBrowserFrameView::InitVirtualKeyboard() {
  if (keyboard_)
    return;

  Profile* keyboard_profile = browser_view()->browser()->profile();
  DCHECK(keyboard_profile) << "Profile required for virtual keyboard.";

  keyboard_ = new KeyboardContainerView(keyboard_profile,
      browser_view()->browser());
  keyboard_->SetVisible(false);
  AddChildView(keyboard_);
}

void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
  if (should_show_keyboard)
    InitVirtualKeyboard();

  if (should_show_keyboard == keyboard_showing_)
    return;

  DCHECK(keyboard_);

  keyboard_showing_ = should_show_keyboard;
  if (keyboard_showing_) {
    animation_->Show();

    // We don't re-layout the client view until the animation ends (see
    // AnimationEnded below) because we want the client view to occupy the
    // entire height during the animation.
    Layout();
  } else {
    animation_->Hide();

    browser_view()->set_clip_y(ui::Tween::ValueBetween(
          animation_->GetCurrentValue(), 0, kKeyboardHeight));
    parent()->Layout();
  }
}

TouchBrowserFrameView::VirtualKeyboardType
    TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {
  if (!view)
    return NONE;

  std::string cname = view->GetClassName();
  if (cname == views::Textfield::kViewClassName) {
    return GENERIC;
  } else if (cname == RenderWidgetHostViewViews::kViewClassName) {
    TabContents* contents = browser_view()->browser()->GetSelectedTabContents();
    bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
        contents->property_bag()) : NULL;
    if (editable && *editable)
      return GENERIC;
  }
  return NONE;
}

bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {
  if (OpaqueBrowserFrameView::HitTest(point))
    return true;

  if (close_button()->IsVisible() &&
      close_button()->GetMirroredBounds().Contains(point))
    return true;
  if (restore_button()->IsVisible() &&
      restore_button()->GetMirroredBounds().Contains(point))
    return true;
  if (maximize_button()->IsVisible() &&
      maximize_button()->GetMirroredBounds().Contains(point))
    return true;
  if (minimize_button()->IsVisible() &&
      minimize_button()->GetMirroredBounds().Contains(point))
    return true;

  return false;
}

void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,
                                          TabContentsWrapper* new_contents,
                                          int index,
                                          bool user_gesture) {
  if (new_contents == old_contents)
    return;

  TabContents* contents = new_contents->tab_contents();
  if (!TabContentsHasFocus(contents))
    return;

  bool* editable = GetFocusedStateAccessor()->GetProperty(
      contents->property_bag());
  UpdateKeyboardAndLayout(editable ? *editable : false);
}

void TouchBrowserFrameView::Observe(NotificationType type,
                                    const NotificationSource& source,
                                    const NotificationDetails& details) {
  Browser* browser = browser_view()->browser();
  if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
    // Only modify the keyboard state if the currently active tab sent the
    // notification.
    const TabContents* current_tab = browser->GetSelectedTabContents();
    TabContents* source_tab = Source<TabContents>(source).ptr();
    const bool editable = *Details<const bool>(details).ptr();

    if (current_tab == source_tab && TabContentsHasFocus(source_tab))
      UpdateKeyboardAndLayout(editable);

    // Save the state of the focused field so that the keyboard visibility
    // can be determined after tab switching.
    GetFocusedStateAccessor()->SetProperty(
        source_tab->property_bag(), editable);
  } else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
    NavigationController* controller =
        Source<NavigationController>(source).ptr();
    Browser* source_browser = Browser::GetBrowserForController(
        controller, NULL);

    // If the Browser for the keyboard has navigated, re-evaluate the visibility
    // of the keyboard.
    TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE;
    views::View* view = GetFocusManager()->GetFocusedView();
    if (view) {
      if (view->GetClassName() == views::Textfield::kViewClassName)
        keyboard_type = GENERIC;
      if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) {
        // Reset the state of the focused field in the current tab.
        GetFocusedStateAccessor()->SetProperty(
            controller->tab_contents()->property_bag(), false);
      }
    }
    if (source_browser == browser)
      UpdateKeyboardAndLayout(keyboard_type == GENERIC);
  } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
    GetFocusedStateAccessor()->DeleteProperty(
        Source<TabContents>(source).ptr()->property_bag());
  } else if (type == NotificationType::PREF_CHANGED) {
    OpaqueBrowserFrameView::Observe(type, source, details);
  }
}

///////////////////////////////////////////////////////////////////////////////
// ui::AnimationDelegate implementation
void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {
  ui::Transform transform;
  transform.SetTranslateY(
      ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));
  keyboard_->SetTransform(transform);
  browser_view()->set_clip_y(
      ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));
  SchedulePaint();
}

void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {
  browser_view()->set_clip_y(0);
  if (keyboard_showing_) {
    // Because the NonClientFrameView is a sibling of the ClientView, we rely on
    // the parent to resize the ClientView instead of resizing it directly.
    parent()->Layout();

    // The keyboard that pops up may end up hiding the text entry. So make sure
    // the renderer scrolls when necessary to keep the textfield visible.
    RenderViewHost* host =
        browser_view()->browser()->GetSelectedTabContents()->render_view_host();
    host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView(
        host->routing_id()));
  }
  SchedulePaint();
}
<commit_msg>Add a missing head to fix touch compile.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "content/common/view_messages.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/transform.h"
#include "views/controls/button/image_button.h"
#include "views/controls/textfield/textfield.h"
#include "views/focus/focus_manager.h"

namespace {

const int kKeyboardHeight = 300;
const int kKeyboardSlideDuration = 500;  // In milliseconds

PropertyAccessor<bool>* GetFocusedStateAccessor() {
  static PropertyAccessor<bool> state;
  return &state;
}

bool TabContentsHasFocus(const TabContents* contents) {
  views::View* view = static_cast<TabContentsViewTouch*>(contents->view());
  return view->Contains(view->GetFocusManager()->GetFocusedView());
}

}  // namespace

// static
const char TouchBrowserFrameView::kViewClassName[] =
    "browser/ui/touch/frame/TouchBrowserFrameView";

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, public:

TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,
                                             BrowserView* browser_view)
    : OpaqueBrowserFrameView(frame, browser_view),
      keyboard_showing_(false),
      focus_listener_added_(false),
      keyboard_(NULL) {
  registrar_.Add(this,
                 NotificationType::NAV_ENTRY_COMMITTED,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::FOCUS_CHANGED_IN_PAGE,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::TAB_CONTENTS_DESTROYED,
                 NotificationService::AllSources());

  browser_view->browser()->tabstrip_model()->AddObserver(this);

  animation_.reset(new ui::SlideAnimation(this));
  animation_->SetTweenType(ui::Tween::LINEAR);
  animation_->SetSlideDuration(kKeyboardSlideDuration);
}

TouchBrowserFrameView::~TouchBrowserFrameView() {
  browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
}

std::string TouchBrowserFrameView::GetClassName() const {
  return kViewClassName;
}

void TouchBrowserFrameView::Layout() {
  OpaqueBrowserFrameView::Layout();

  if (!keyboard_)
    return;

  keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());
  gfx::Rect bounds = GetBoundsForReservedArea();
  if (animation_->is_animating() && !keyboard_showing_) {
    // The keyboard is in the process of hiding. So pretend it still has the
    // same bounds as when the keyboard is visible. But
    // |GetBoundsForReservedArea| should not take this into account so that the
    // render view gets the entire area to relayout itself.
    bounds.set_y(bounds.y() - kKeyboardHeight);
    bounds.set_height(kKeyboardHeight);
  }
  keyboard_->SetBoundsRect(bounds);
}

void TouchBrowserFrameView::FocusWillChange(views::View* focused_before,
                                            views::View* focused_now) {
  VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
  VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
  if (before != now) {
    // TODO(varunjain): support other types of keyboard.
    UpdateKeyboardAndLayout(now == GENERIC);
  }
}

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, protected:
int TouchBrowserFrameView::GetReservedHeight() const {
  return keyboard_showing_ ? kKeyboardHeight : 0;
}

void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,
                                                 View* parent,
                                                 View* child) {
  OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);
  if (!GetFocusManager())
    return;

  if (is_add && !focus_listener_added_) {
    // Add focus listener when this view is added to the hierarchy.
    GetFocusManager()->AddFocusChangeListener(this);
    focus_listener_added_ = true;
  } else if (!is_add && focus_listener_added_) {
    // Remove focus listener when this view is removed from the hierarchy.
    GetFocusManager()->RemoveFocusChangeListener(this);
    focus_listener_added_ = false;
  }
}

///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, private:

void TouchBrowserFrameView::InitVirtualKeyboard() {
  if (keyboard_)
    return;

  Profile* keyboard_profile = browser_view()->browser()->profile();
  DCHECK(keyboard_profile) << "Profile required for virtual keyboard.";

  keyboard_ = new KeyboardContainerView(keyboard_profile,
      browser_view()->browser());
  keyboard_->SetVisible(false);
  AddChildView(keyboard_);
}

void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
  if (should_show_keyboard)
    InitVirtualKeyboard();

  if (should_show_keyboard == keyboard_showing_)
    return;

  DCHECK(keyboard_);

  keyboard_showing_ = should_show_keyboard;
  if (keyboard_showing_) {
    animation_->Show();

    // We don't re-layout the client view until the animation ends (see
    // AnimationEnded below) because we want the client view to occupy the
    // entire height during the animation.
    Layout();
  } else {
    animation_->Hide();

    browser_view()->set_clip_y(ui::Tween::ValueBetween(
          animation_->GetCurrentValue(), 0, kKeyboardHeight));
    parent()->Layout();
  }
}

TouchBrowserFrameView::VirtualKeyboardType
    TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {
  if (!view)
    return NONE;

  std::string cname = view->GetClassName();
  if (cname == views::Textfield::kViewClassName) {
    return GENERIC;
  } else if (cname == RenderWidgetHostViewViews::kViewClassName) {
    TabContents* contents = browser_view()->browser()->GetSelectedTabContents();
    bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
        contents->property_bag()) : NULL;
    if (editable && *editable)
      return GENERIC;
  }
  return NONE;
}

bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {
  if (OpaqueBrowserFrameView::HitTest(point))
    return true;

  if (close_button()->IsVisible() &&
      close_button()->GetMirroredBounds().Contains(point))
    return true;
  if (restore_button()->IsVisible() &&
      restore_button()->GetMirroredBounds().Contains(point))
    return true;
  if (maximize_button()->IsVisible() &&
      maximize_button()->GetMirroredBounds().Contains(point))
    return true;
  if (minimize_button()->IsVisible() &&
      minimize_button()->GetMirroredBounds().Contains(point))
    return true;

  return false;
}

void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,
                                          TabContentsWrapper* new_contents,
                                          int index,
                                          bool user_gesture) {
  if (new_contents == old_contents)
    return;

  TabContents* contents = new_contents->tab_contents();
  if (!TabContentsHasFocus(contents))
    return;

  bool* editable = GetFocusedStateAccessor()->GetProperty(
      contents->property_bag());
  UpdateKeyboardAndLayout(editable ? *editable : false);
}

void TouchBrowserFrameView::Observe(NotificationType type,
                                    const NotificationSource& source,
                                    const NotificationDetails& details) {
  Browser* browser = browser_view()->browser();
  if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
    // Only modify the keyboard state if the currently active tab sent the
    // notification.
    const TabContents* current_tab = browser->GetSelectedTabContents();
    TabContents* source_tab = Source<TabContents>(source).ptr();
    const bool editable = *Details<const bool>(details).ptr();

    if (current_tab == source_tab && TabContentsHasFocus(source_tab))
      UpdateKeyboardAndLayout(editable);

    // Save the state of the focused field so that the keyboard visibility
    // can be determined after tab switching.
    GetFocusedStateAccessor()->SetProperty(
        source_tab->property_bag(), editable);
  } else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
    NavigationController* controller =
        Source<NavigationController>(source).ptr();
    Browser* source_browser = Browser::GetBrowserForController(
        controller, NULL);

    // If the Browser for the keyboard has navigated, re-evaluate the visibility
    // of the keyboard.
    TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE;
    views::View* view = GetFocusManager()->GetFocusedView();
    if (view) {
      if (view->GetClassName() == views::Textfield::kViewClassName)
        keyboard_type = GENERIC;
      if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) {
        // Reset the state of the focused field in the current tab.
        GetFocusedStateAccessor()->SetProperty(
            controller->tab_contents()->property_bag(), false);
      }
    }
    if (source_browser == browser)
      UpdateKeyboardAndLayout(keyboard_type == GENERIC);
  } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
    GetFocusedStateAccessor()->DeleteProperty(
        Source<TabContents>(source).ptr()->property_bag());
  } else if (type == NotificationType::PREF_CHANGED) {
    OpaqueBrowserFrameView::Observe(type, source, details);
  }
}

///////////////////////////////////////////////////////////////////////////////
// ui::AnimationDelegate implementation
void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {
  ui::Transform transform;
  transform.SetTranslateY(
      ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));
  keyboard_->SetTransform(transform);
  browser_view()->set_clip_y(
      ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));
  SchedulePaint();
}

void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {
  browser_view()->set_clip_y(0);
  if (keyboard_showing_) {
    // Because the NonClientFrameView is a sibling of the ClientView, we rely on
    // the parent to resize the ClientView instead of resizing it directly.
    parent()->Layout();

    // The keyboard that pops up may end up hiding the text entry. So make sure
    // the renderer scrolls when necessary to keep the textfield visible.
    RenderViewHost* host =
        browser_view()->browser()->GetSelectedTabContents()->render_view_host();
    host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView(
        host->routing_id()));
  }
  SchedulePaint();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: odma_lib.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:58:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
//#ifndef _OSL_PROCESS_H_
//#include <osl/process.h>
//#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef ODMA_LIB_HXX
#include "odma_lib.hxx"
#endif

namespace odma
{

    TODMRegisterApp         pODMRegisterApp;
    TODMUnRegisterApp       pODMUnRegisterApp;
    TODMSelectDoc           pODMSelectDoc;
    TODMOpenDoc             pODMOpenDoc;
    TODMSaveDoc             pODMSaveDoc;
    TODMCloseDoc            pODMCloseDoc;
    TODMNewDoc              pODMNewDoc;
    TODMSaveAs              pODMSaveAs;
    TODMActivate            pODMActivate;
    TODMGetDocInfo          pODMGetDocInfo;
    TODMSetDocInfo          pODMSetDocInfo;
    TODMGetDMSInfo          pODMGetDMSInfo;
    TODMGetDMSCount         pODMGetDMSCount;
    TODMGetDMSList          pODMGetDMSList;
    TODMGetDMS              pODMGetDMS;
    TODMSetDMS              pODMSetDMS;
    TODMQueryExecute        pODMQueryExecute;
    TODMQueryGetResults     pODMQueryGetResults;
    TODMQueryClose          pODMQueryClose;
    TODMCloseDocEx          pODMCloseDocEx;
    TODMSaveAsEx            pODMSaveAsEx;
    TODMSaveDocEx           pODMSaveDocEx;
    TODMSelectDocEx         pODMSelectDocEx;
    TODMQueryCapability     pODMQueryCapability;
    TODMSetDocEvent         pODMSetDocEvent;
    TODMGetAlternateContent pODMGetAlternateContent;
    TODMSetAlternateContent pODMSetAlternateContent;
    TODMGetDocRelation      pODMGetDocRelation;
    TODMSetDocRelation      pODMSetDocRelation;

    sal_Bool LoadFunctions(oslModule _pODMA);

    sal_Bool LoadLibrary()
    {
        static sal_Bool bLoaded = sal_False;
        static oslModule pODMA = NULL;

        if (bLoaded)
            return sal_True;
        ::rtl::OUString sPath;
    #ifdef WIN
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA.DLL"));

    #endif
    #ifdef WNT
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA32.DLL"));
    #endif
    #ifdef UNX
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("libodma.so"));
    #endif

        pODMA = osl_loadModule( sPath.pData,SAL_LOADMODULE_NOW );
        if( !pODMA)
            return sal_False;

        return bLoaded = LoadFunctions(pODMA);
    }
    // -------------------------------------------------------------------------

    sal_Bool LoadFunctions(oslModule pODMA)
    {
        if ( ( pODMRegisterApp = (TODMRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMRegisterApp")).pData)) == NULL ) return sal_False;
        if ( ( pODMUnRegisterApp = (TODMUnRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMUnRegisterApp")).pData)) == NULL ) return sal_False;
        if ( ( pODMSelectDoc = (TODMSelectDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMOpenDoc = (TODMOpenDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMOpenDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveDoc = (TODMSaveDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMCloseDoc = (TODMCloseDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMNewDoc = (TODMNewDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMNewDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveAs = (TODMSaveAs)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAs")).pData)) == NULL ) return sal_False;
        if ( ( pODMActivate = (TODMActivate)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMActivate")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDocInfo = (TODMGetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocInfo = (TODMSetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSInfo = (TODMGetDMSInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSCount = (TODMGetDMSCount)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSCount")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSList = (TODMGetDMSList)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSList")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMS = (TODMGetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMS")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDMS = (TODMSetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDMS")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryExecute = (TODMQueryExecute)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryExecute")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryGetResults = (TODMQueryGetResults)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryGetResults")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryClose = (TODMQueryClose)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryClose")).pData)) == NULL ) return sal_False;
        if ( ( pODMCloseDocEx = (TODMCloseDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveAsEx = (TODMSaveAsEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAsEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveDocEx = (TODMSaveDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSelectDocEx = (TODMSelectDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryCapability = (TODMQueryCapability)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryCapability")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocEvent = (TODMSetDocEvent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocEvent")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetAlternateContent = (TODMGetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetAlternateContent")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetAlternateContent = (TODMSetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetAlternateContent")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDocRelation = (TODMGetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocRelation")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocRelation = (TODMSetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocRelation")).pData)) == NULL ) return sal_False;
        return sal_True;
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.118); FILE MERGED 2008/04/01 16:02:21 thb 1.5.118.3: #i85898# Stripping all external header guards 2008/04/01 12:58:20 thb 1.5.118.2: #i85898# Stripping all external header guards 2008/03/31 15:30:26 rt 1.5.118.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: odma_lib.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
//#ifndef _OSL_PROCESS_H_
//#include <osl/process.h>
//#endif
#include <osl/module.h>
#include <rtl/ustring.hxx>
#include "odma_lib.hxx"

namespace odma
{

    TODMRegisterApp         pODMRegisterApp;
    TODMUnRegisterApp       pODMUnRegisterApp;
    TODMSelectDoc           pODMSelectDoc;
    TODMOpenDoc             pODMOpenDoc;
    TODMSaveDoc             pODMSaveDoc;
    TODMCloseDoc            pODMCloseDoc;
    TODMNewDoc              pODMNewDoc;
    TODMSaveAs              pODMSaveAs;
    TODMActivate            pODMActivate;
    TODMGetDocInfo          pODMGetDocInfo;
    TODMSetDocInfo          pODMSetDocInfo;
    TODMGetDMSInfo          pODMGetDMSInfo;
    TODMGetDMSCount         pODMGetDMSCount;
    TODMGetDMSList          pODMGetDMSList;
    TODMGetDMS              pODMGetDMS;
    TODMSetDMS              pODMSetDMS;
    TODMQueryExecute        pODMQueryExecute;
    TODMQueryGetResults     pODMQueryGetResults;
    TODMQueryClose          pODMQueryClose;
    TODMCloseDocEx          pODMCloseDocEx;
    TODMSaveAsEx            pODMSaveAsEx;
    TODMSaveDocEx           pODMSaveDocEx;
    TODMSelectDocEx         pODMSelectDocEx;
    TODMQueryCapability     pODMQueryCapability;
    TODMSetDocEvent         pODMSetDocEvent;
    TODMGetAlternateContent pODMGetAlternateContent;
    TODMSetAlternateContent pODMSetAlternateContent;
    TODMGetDocRelation      pODMGetDocRelation;
    TODMSetDocRelation      pODMSetDocRelation;

    sal_Bool LoadFunctions(oslModule _pODMA);

    sal_Bool LoadLibrary()
    {
        static sal_Bool bLoaded = sal_False;
        static oslModule pODMA = NULL;

        if (bLoaded)
            return sal_True;
        ::rtl::OUString sPath;
    #ifdef WIN
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA.DLL"));

    #endif
    #ifdef WNT
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA32.DLL"));
    #endif
    #ifdef UNX
        sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("libodma.so"));
    #endif

        pODMA = osl_loadModule( sPath.pData,SAL_LOADMODULE_NOW );
        if( !pODMA)
            return sal_False;

        return bLoaded = LoadFunctions(pODMA);
    }
    // -------------------------------------------------------------------------

    sal_Bool LoadFunctions(oslModule pODMA)
    {
        if ( ( pODMRegisterApp = (TODMRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMRegisterApp")).pData)) == NULL ) return sal_False;
        if ( ( pODMUnRegisterApp = (TODMUnRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMUnRegisterApp")).pData)) == NULL ) return sal_False;
        if ( ( pODMSelectDoc = (TODMSelectDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMOpenDoc = (TODMOpenDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMOpenDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveDoc = (TODMSaveDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMCloseDoc = (TODMCloseDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMNewDoc = (TODMNewDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMNewDoc")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveAs = (TODMSaveAs)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAs")).pData)) == NULL ) return sal_False;
        if ( ( pODMActivate = (TODMActivate)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMActivate")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDocInfo = (TODMGetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocInfo = (TODMSetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSInfo = (TODMGetDMSInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSInfo")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSCount = (TODMGetDMSCount)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSCount")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMSList = (TODMGetDMSList)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSList")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDMS = (TODMGetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMS")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDMS = (TODMSetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDMS")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryExecute = (TODMQueryExecute)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryExecute")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryGetResults = (TODMQueryGetResults)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryGetResults")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryClose = (TODMQueryClose)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryClose")).pData)) == NULL ) return sal_False;
        if ( ( pODMCloseDocEx = (TODMCloseDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveAsEx = (TODMSaveAsEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAsEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSaveDocEx = (TODMSaveDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMSelectDocEx = (TODMSelectDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDocEx")).pData)) == NULL ) return sal_False;
        if ( ( pODMQueryCapability = (TODMQueryCapability)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryCapability")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocEvent = (TODMSetDocEvent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocEvent")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetAlternateContent = (TODMGetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetAlternateContent")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetAlternateContent = (TODMSetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetAlternateContent")).pData)) == NULL ) return sal_False;
        if ( ( pODMGetDocRelation = (TODMGetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocRelation")).pData)) == NULL ) return sal_False;
        if ( ( pODMSetDocRelation = (TODMSetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocRelation")).pData)) == NULL ) return sal_False;
        return sal_True;
    }
}
<|endoftext|>


<commit_before>/* Original Work Copyright (c) 2012-2014 Alexander Turkin
   Modified 2014 by William Hallatt

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cmath>
#include <algorithm>

#include <QtGui/QPainter>
#include <QtCore/QTimer>

#include "QtWaitingSpinner.h"

/*----------------------------------------------------------------------------*/

// Defaults
const QColor c_color(Qt::black);
const qreal c_roundness(70.0);
const qreal c_minTrailOpacity(15.0);
const qreal c_trailFadePercentage(70.0);
const int c_lines(12);
const int c_lineLength(10);
const int c_lineWidth(5);
const int c_innerRadius(10);
const int c_revPerSec(1);

/*----------------------------------------------------------------------------*/

QtWaitingSpinner::QtWaitingSpinner(QWidget *parent)
    : QWidget(parent),

      // Configurable settings.
      m_color(c_color), m_roundness(c_roundness),
      m_minTrailOpacity(c_minTrailOpacity),
      m_trailFadePercentage(c_trailFadePercentage), m_revPerSec(c_revPerSec),
      m_numberOfLines(c_lines), m_lineLength(c_lineLength + c_lineWidth),
      m_lineWidth(c_lineWidth), m_innerRadius(c_innerRadius),

      // Other
      m_timer(NULL), m_parent(parent), m_centreOnParent(false),
      m_currentCounter(0) {
  initialise();
}

/*----------------------------------------------------------------------------*/

QtWaitingSpinner::QtWaitingSpinner(Qt::WindowModality modality, QWidget *parent,
                                   bool centreOnParent)
    : QWidget(parent, Qt::Dialog | Qt::FramelessWindowHint),

      // Configurable settings.
      m_color(c_color), m_roundness(c_roundness),
      m_minTrailOpacity(c_minTrailOpacity),
      m_trailFadePercentage(c_trailFadePercentage), m_revPerSec(c_revPerSec),
      m_numberOfLines(c_lines), m_lineLength(c_lineLength + c_lineWidth),
      m_lineWidth(c_lineWidth), m_innerRadius(c_innerRadius),

      // Other
      m_timer(NULL), m_parent(parent), m_centreOnParent(centreOnParent),
      m_currentCounter(0) {
  initialise();

  // We need to set the window modality AFTER we've hidden the
  // widget for the first time since changing this property while
  // the widget is visible has no effect.
  this->setWindowModality(modality);
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::initialise() {
  m_timer = new QTimer(this);
  connect(m_timer, SIGNAL(timeout()), this, SLOT(rotate()));
  updateSize();
  updateTimer();
  this->hide();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::paintEvent(QPaintEvent * /*ev*/) {
  QPainter painter(this);
  painter.fillRect(this->rect(), Qt::transparent);
  painter.setRenderHint(QPainter::Antialiasing, true);

  if (m_currentCounter >= m_numberOfLines) {
    m_currentCounter = 0;
  }
  painter.setPen(Qt::NoPen);
  for (int i = 0; i < m_numberOfLines; ++i) {
    painter.save();
    painter.translate(m_innerRadius + m_lineLength,
                      m_innerRadius + m_lineLength);
    qreal rotateAngle =
        static_cast<qreal>(360 * i) / static_cast<qreal>(m_numberOfLines);
    painter.rotate(rotateAngle);
    painter.translate(m_innerRadius, 0);
    int distance =
        lineCountDistanceFromPrimary(i, m_currentCounter, m_numberOfLines);
    QColor color =
        currentLineColor(distance, m_numberOfLines, m_trailFadePercentage,
                         m_minTrailOpacity, m_color);
    painter.setBrush(color);
    // TODO improve the way rounded rect is painted
    painter.drawRoundedRect(
        QRect(0, -m_lineWidth / 2, m_lineLength, m_lineWidth), m_roundness,
        m_roundness, Qt::RelativeSize);
    painter.restore();
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::start() {
  updatePosition();
  this->show();
  if (!m_timer->isActive()) {
    m_timer->start();
    m_currentCounter = 0;
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::stop() {
  this->hide();
  if (m_timer->isActive()) {
    m_timer->stop();
    m_currentCounter = 0;
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setNumberOfLines(int lines) {
  m_numberOfLines = lines;
  m_currentCounter = 0;
  updateTimer();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setLineLength(int length) {
  m_lineLength = length;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setLineWidth(int width) {
  m_lineWidth = width;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setInnerRadius(int radius) {
  m_innerRadius = radius;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setRoundness(qreal roundness) {
  m_roundness = std::max(0.0, std::min(100.0, roundness));
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setColor(QColor color) { m_color = color; }

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setRevolutionsPerSecond(int rps) {
  m_revPerSec = rps;
  updateTimer();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setTrailFadePercentage(qreal trail) {
  m_trailFadePercentage = trail;
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setMinimumTrailOpacity(qreal minOpacity) {
  m_minTrailOpacity = minOpacity;
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::rotate() {
  ++m_currentCounter;
  if (m_currentCounter >= m_numberOfLines) {
    m_currentCounter = 0;
  }
  update();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updateSize() {
  int size = (m_innerRadius + m_lineLength) * 2;
  setFixedSize(size, size);
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updateTimer() {
  m_timer->setInterval(calculateTimerInterval(m_numberOfLines, m_revPerSec));
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updatePosition() {
  if (m_parent && m_centreOnParent) {
    this->move(m_parent->frameGeometry().topLeft() + m_parent->rect().center() -
               this->rect().center());
  }
}

/*----------------------------------------------------------------------------*/

int QtWaitingSpinner::calculateTimerInterval(int lines, int speed) {
  return 1000 / (lines * speed);
}

/*----------------------------------------------------------------------------*/

int QtWaitingSpinner::lineCountDistanceFromPrimary(int current, int primary,
                                                   int totalNrOfLines) {
  int distance = primary - current;
  if (distance < 0) {
    distance += totalNrOfLines;
  }
  return distance;
}

/*----------------------------------------------------------------------------*/

QColor QtWaitingSpinner::currentLineColor(int countDistance, int totalNrOfLines,
                                          qreal trailFadePerc, qreal minOpacity,
                                          QColor color) {
  if (countDistance == 0) {
    return color;
  }
  const qreal minAlphaF = minOpacity / 100.0;
  int distanceThreshold =
      static_cast<int>(ceil((totalNrOfLines - 1) * trailFadePerc / 100.0));
  if (countDistance > distanceThreshold) {
    color.setAlphaF(minAlphaF);
  } else {
    qreal alphaDiff = color.alphaF() - minAlphaF;
    qreal gradient = alphaDiff / static_cast<qreal>(distanceThreshold + 1);
    qreal resultAlpha = color.alphaF() - gradient * countDistance;

    // If alpha is out of bounds, clip it.
    resultAlpha = std::min(1.0, std::max(0.0, resultAlpha));
    color.setAlphaF(resultAlpha);
  }
  return color;
}

/*----------------------------------------------------------------------------*/
<commit_msg>Got rid of the popup spinner's square container by setting translucent background attribute.<commit_after>/* Original Work Copyright (c) 2012-2014 Alexander Turkin
   Modified 2014 by William Hallatt

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cmath>
#include <algorithm>

#include <QtGui/QPainter>
#include <QtCore/QTimer>

#include "QtWaitingSpinner.h"

/*----------------------------------------------------------------------------*/

// Defaults
const QColor c_color(Qt::black);
const qreal c_roundness(70.0);
const qreal c_minTrailOpacity(15.0);
const qreal c_trailFadePercentage(70.0);
const int c_lines(12);
const int c_lineLength(10);
const int c_lineWidth(5);
const int c_innerRadius(10);
const int c_revPerSec(1);

/*----------------------------------------------------------------------------*/

QtWaitingSpinner::QtWaitingSpinner(QWidget *parent)
    : QWidget(parent),

      // Configurable settings.
      m_color(c_color), m_roundness(c_roundness),
      m_minTrailOpacity(c_minTrailOpacity),
      m_trailFadePercentage(c_trailFadePercentage), m_revPerSec(c_revPerSec),
      m_numberOfLines(c_lines), m_lineLength(c_lineLength + c_lineWidth),
      m_lineWidth(c_lineWidth), m_innerRadius(c_innerRadius),

      // Other
      m_timer(NULL), m_parent(parent), m_centreOnParent(false),
      m_currentCounter(0) {
  initialise();
}

/*----------------------------------------------------------------------------*/

QtWaitingSpinner::QtWaitingSpinner(Qt::WindowModality modality, QWidget *parent,
                                   bool centreOnParent)
    : QWidget(parent, Qt::Dialog | Qt::FramelessWindowHint),

      // Configurable settings.
      m_color(c_color), m_roundness(c_roundness),
      m_minTrailOpacity(c_minTrailOpacity),
      m_trailFadePercentage(c_trailFadePercentage), m_revPerSec(c_revPerSec),
      m_numberOfLines(c_lines), m_lineLength(c_lineLength + c_lineWidth),
      m_lineWidth(c_lineWidth), m_innerRadius(c_innerRadius),

      // Other
      m_timer(NULL), m_parent(parent), m_centreOnParent(centreOnParent),
      m_currentCounter(0) {
  initialise();

  // We need to set the window modality AFTER we've hidden the
  // widget for the first time since changing this property while
  // the widget is visible has no effect.
  this->setWindowModality(modality);
  this->setAttribute(Qt::WA_TranslucentBackground);
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::initialise() {
  m_timer = new QTimer(this);
  connect(m_timer, SIGNAL(timeout()), this, SLOT(rotate()));
  updateSize();
  updateTimer();
  this->hide();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::paintEvent(QPaintEvent * /*ev*/) {
  QPainter painter(this);
  painter.fillRect(this->rect(), Qt::transparent);
  painter.setRenderHint(QPainter::Antialiasing, true);

  if (m_currentCounter >= m_numberOfLines) {
    m_currentCounter = 0;
  }
  painter.setPen(Qt::NoPen);
  for (int i = 0; i < m_numberOfLines; ++i) {
    painter.save();
    painter.translate(m_innerRadius + m_lineLength,
                      m_innerRadius + m_lineLength);
    qreal rotateAngle =
        static_cast<qreal>(360 * i) / static_cast<qreal>(m_numberOfLines);
    painter.rotate(rotateAngle);
    painter.translate(m_innerRadius, 0);
    int distance =
        lineCountDistanceFromPrimary(i, m_currentCounter, m_numberOfLines);
    QColor color =
        currentLineColor(distance, m_numberOfLines, m_trailFadePercentage,
                         m_minTrailOpacity, m_color);
    painter.setBrush(color);
    // TODO improve the way rounded rect is painted
    painter.drawRoundedRect(
        QRect(0, -m_lineWidth / 2, m_lineLength, m_lineWidth), m_roundness,
        m_roundness, Qt::RelativeSize);
    painter.restore();
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::start() {
  updatePosition();
  this->show();
  if (!m_timer->isActive()) {
    m_timer->start();
    m_currentCounter = 0;
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::stop() {
  this->hide();
  if (m_timer->isActive()) {
    m_timer->stop();
    m_currentCounter = 0;
  }
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setNumberOfLines(int lines) {
  m_numberOfLines = lines;
  m_currentCounter = 0;
  updateTimer();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setLineLength(int length) {
  m_lineLength = length;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setLineWidth(int width) {
  m_lineWidth = width;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setInnerRadius(int radius) {
  m_innerRadius = radius;
  updateSize();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setRoundness(qreal roundness) {
  m_roundness = std::max(0.0, std::min(100.0, roundness));
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setColor(QColor color) { m_color = color; }

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setRevolutionsPerSecond(int rps) {
  m_revPerSec = rps;
  updateTimer();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setTrailFadePercentage(qreal trail) {
  m_trailFadePercentage = trail;
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::setMinimumTrailOpacity(qreal minOpacity) {
  m_minTrailOpacity = minOpacity;
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::rotate() {
  ++m_currentCounter;
  if (m_currentCounter >= m_numberOfLines) {
    m_currentCounter = 0;
  }
  update();
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updateSize() {
  int size = (m_innerRadius + m_lineLength) * 2;
  setFixedSize(size, size);
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updateTimer() {
  m_timer->setInterval(calculateTimerInterval(m_numberOfLines, m_revPerSec));
}

/*----------------------------------------------------------------------------*/

void QtWaitingSpinner::updatePosition() {
  if (m_parent && m_centreOnParent) {
    this->move(m_parent->frameGeometry().topLeft() + m_parent->rect().center() -
               this->rect().center());
  }
}

/*----------------------------------------------------------------------------*/

int QtWaitingSpinner::calculateTimerInterval(int lines, int speed) {
  return 1000 / (lines * speed);
}

/*----------------------------------------------------------------------------*/

int QtWaitingSpinner::lineCountDistanceFromPrimary(int current, int primary,
                                                   int totalNrOfLines) {
  int distance = primary - current;
  if (distance < 0) {
    distance += totalNrOfLines;
  }
  return distance;
}

/*----------------------------------------------------------------------------*/

QColor QtWaitingSpinner::currentLineColor(int countDistance, int totalNrOfLines,
                                          qreal trailFadePerc, qreal minOpacity,
                                          QColor color) {
  if (countDistance == 0) {
    return color;
  }
  const qreal minAlphaF = minOpacity / 100.0;
  int distanceThreshold =
      static_cast<int>(ceil((totalNrOfLines - 1) * trailFadePerc / 100.0));
  if (countDistance > distanceThreshold) {
    color.setAlphaF(minAlphaF);
  } else {
    qreal alphaDiff = color.alphaF() - minAlphaF;
    qreal gradient = alphaDiff / static_cast<qreal>(distanceThreshold + 1);
    qreal resultAlpha = color.alphaF() - gradient * countDistance;

    // If alpha is out of bounds, clip it.
    resultAlpha = std::min(1.0, std::max(0.0, resultAlpha));
    color.setAlphaF(resultAlpha);
  }
  return color;
}

/*----------------------------------------------------------------------------*/
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/util/Base64Codec.h"
#include "db/util/StringTools.h"

using namespace std;
using namespace db::util;

const char Base64Codec::sIndexToBase64[] =
{
   /*  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12, */
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',

   /* 13,  14,  15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, */
     'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

   /* 26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38, */
     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',

   /* 39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, */
     'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

   /* 52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63 */
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

const short Base64Codec::sBase64ToIndex[] =
{
   /* 43 -43 = 0*/
   /* '+',  1,  2,  3,'/' */
       62, -1, -1, -1, 63,

   /* '0','1','2','3','4','5','6','7','8','9' */
       52, 53, 54, 55, 56, 57, 58, 59, 60, 61,

   /* 15, 16, 17,'=', 19, 20, 21 */
      -1, -1, -1, -2, -1, -1, -1,

   /* 65 - 43 = 22*/
   /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,

   /* 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
       13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,

   /* 91 - 43 = 48 */
   /* 48, 49, 50, 51, 52, 53 */
      -1, -1, -1, -1, -1, -1,

   /* 97 - 43 = 54*/
   /* 'a','b','c','d','e','f','g','h','i','j','k','l','m' */
       26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,

   /* 'n','o','p','q','r','s','t','u','v','w','x','y','z' */
       39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};

short Base64Codec::charToShort(char c)
{
   return sBase64ToIndex[c - 43];
}

void Base64Codec::encodeGroup(
   const char* data, unsigned int length, char* group)
{
   unsigned short b0 = data[0] & 0xff;
   unsigned short b1 = (length > 1) ? data[1] & 0xff : 0;
   unsigned short b2 = (length > 2) ? data[2] & 0xff : 0;

   group[0] = sIndexToBase64[b0 >> 2];
   group[1] = sIndexToBase64[(b0 << 4 | b1 >> 4) & 0x3f];
   group[2] = (length > 1) ? sIndexToBase64[(b1 << 2 | b2 >> 6) & 0x3f] : '=';
   group[3] = (length > 2) ? sIndexToBase64[b2 & 0x3f] : '=';
}

void Base64Codec::decodeGroup(
   const char* str, char* bytes, unsigned int& length)
{
   // get 6-bit integer values
   short index[4];
   for(short i = 0; i < 4; i++)
   {
   	index[i] = charToShort(str[i]);
   }

   // this byte will definitely be used, padding or not
   char b0 = (char)(index[0] << 2 | index[1] >> 4);

   // determine how many bytes we'll be decoding to and decode
   // -2 maps is the padding character '='
   if(index[2] == -2)
   {
   	// 1 decoded byte
   	length = 1;
      bytes[0] = b0;
   }
   else if(index[3] == -2)
   {
   	// 2 decoded bytes
      length = 2;
      bytes[0] = b0;
      bytes[1] = (char)(index[1] << 4 | index[2] >> 2);
   }
   else
   {
   	// 3 decoded bytes
      length = 3;
      bytes[0] = b0;
      bytes[1] = (char)(index[1] << 4 | index[2] >> 2);
      bytes[2] = (char)(index[2] << 6 | index[3]);
   }
}

string Base64Codec::encode(const char* data, unsigned int length)
{
   string rval;

   if(data != NULL && length > 0)
   {
      // Base64 encoding requires 24 bit groups, and each
      // byte is 8 bits, so the data should be broken into groups
      // of 3 bytes each
      unsigned int groups = length / 3;

      // see if there is an incomplete group
      if(groups * 3 != length)
      {
         groups++;
      }

      // encode all the groups
      char group[4];
      unsigned int offset = 0;
      unsigned int lineLength = 0;
      for(unsigned int i = 0; i < groups; i++, offset += 3)
      {
         // encode the group
         encodeGroup(data + offset, length - offset, group);

         // Base64 allows no more than 76 characters per line
         // if the line length is greater 76, then insert a line break
         if(lineLength + 4 > 76)
         {
            rval.push_back('\r');
            rval.push_back('\n');
            lineLength = 0;
         }

         // update line length
         lineLength += 4;

         // add the group to the buffer
         rval.append(group, 4);
      }
   }

   return rval;
}

void Base64Codec::decode(const string& str, char** data, unsigned int& length)
{
   // point data at NULL and set length to 0
   *data = NULL;
   length = 0;

   // remove all white space
   char temp[str.length()];
   unsigned int len = 0;
   for(unsigned int i = 0; i < str.length(); i++)
   {
      if(str[i] != ' ' && str[i] != '\t' &&
         str[i] != '\r' && str[i] != '\n')
      {
         temp[len++] = str[i];
      }
   }
   temp[len] = 0;

   // make sure the string is at least 4 characters
   if(len > 3)
   {
      // get and check the number of groups, must be a multiple of 4
      unsigned int groups = len / 4;
      if(groups * 4 == len)
      {
         // get the number of pad characters
         unsigned int padChars = 0;
         if(temp[len - 2] == '=')
         {
            padChars = 2;
         }
         else if(temp[len - 1] == '=')
         {
            padChars = 1;
         }

         // calculate the decoded length, it should be the number of
         // groups * 3 - padBytes
         length = groups * 3 - padChars;

         // allocate space for the byte array
         *data = (char*)malloc(length);

         // decode all the groups
         char bytes[3];
         unsigned int dataIndex = 0;
         unsigned int strIndex = 0;
         for(unsigned int i = 0; i < groups; i++, strIndex += 4)
         {
            // copy the decoded bytes into the decoded buffer
            decodeGroup(temp + strIndex, bytes, len);
            memcpy((*data) + dataIndex, bytes, len);
            dataIndex += len;
         }
      }
   }
}
<commit_msg>Removed unnecessary include of StringTools.h.<commit_after>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/util/Base64Codec.h"

using namespace std;
using namespace db::util;

const char Base64Codec::sIndexToBase64[] =
{
   /*  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12, */
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',

   /* 13,  14,  15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, */
     'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

   /* 26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38, */
     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',

   /* 39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, */
     'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

   /* 52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63 */
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

const short Base64Codec::sBase64ToIndex[] =
{
   /* 43 -43 = 0*/
   /* '+',  1,  2,  3,'/' */
       62, -1, -1, -1, 63,

   /* '0','1','2','3','4','5','6','7','8','9' */
       52, 53, 54, 55, 56, 57, 58, 59, 60, 61,

   /* 15, 16, 17,'=', 19, 20, 21 */
      -1, -1, -1, -2, -1, -1, -1,

   /* 65 - 43 = 22*/
   /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,

   /* 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
       13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,

   /* 91 - 43 = 48 */
   /* 48, 49, 50, 51, 52, 53 */
      -1, -1, -1, -1, -1, -1,

   /* 97 - 43 = 54*/
   /* 'a','b','c','d','e','f','g','h','i','j','k','l','m' */
       26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,

   /* 'n','o','p','q','r','s','t','u','v','w','x','y','z' */
       39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};

short Base64Codec::charToShort(char c)
{
   return sBase64ToIndex[c - 43];
}

void Base64Codec::encodeGroup(
   const char* data, unsigned int length, char* group)
{
   unsigned short b0 = data[0] & 0xff;
   unsigned short b1 = (length > 1) ? data[1] & 0xff : 0;
   unsigned short b2 = (length > 2) ? data[2] & 0xff : 0;

   group[0] = sIndexToBase64[b0 >> 2];
   group[1] = sIndexToBase64[(b0 << 4 | b1 >> 4) & 0x3f];
   group[2] = (length > 1) ? sIndexToBase64[(b1 << 2 | b2 >> 6) & 0x3f] : '=';
   group[3] = (length > 2) ? sIndexToBase64[b2 & 0x3f] : '=';
}

void Base64Codec::decodeGroup(
   const char* str, char* bytes, unsigned int& length)
{
   // get 6-bit integer values
   short index[4];
   for(short i = 0; i < 4; i++)
   {
   	index[i] = charToShort(str[i]);
   }

   // this byte will definitely be used, padding or not
   char b0 = (char)(index[0] << 2 | index[1] >> 4);

   // determine how many bytes we'll be decoding to and decode
   // -2 maps is the padding character '='
   if(index[2] == -2)
   {
   	// 1 decoded byte
   	length = 1;
      bytes[0] = b0;
   }
   else if(index[3] == -2)
   {
   	// 2 decoded bytes
      length = 2;
      bytes[0] = b0;
      bytes[1] = (char)(index[1] << 4 | index[2] >> 2);
   }
   else
   {
   	// 3 decoded bytes
      length = 3;
      bytes[0] = b0;
      bytes[1] = (char)(index[1] << 4 | index[2] >> 2);
      bytes[2] = (char)(index[2] << 6 | index[3]);
   }
}

string Base64Codec::encode(const char* data, unsigned int length)
{
   string rval;

   if(data != NULL && length > 0)
   {
      // Base64 encoding requires 24 bit groups, and each
      // byte is 8 bits, so the data should be broken into groups
      // of 3 bytes each
      unsigned int groups = length / 3;

      // see if there is an incomplete group
      if(groups * 3 != length)
      {
         groups++;
      }

      // encode all the groups
      char group[4];
      unsigned int offset = 0;
      unsigned int lineLength = 0;
      for(unsigned int i = 0; i < groups; i++, offset += 3)
      {
         // encode the group
         encodeGroup(data + offset, length - offset, group);

         // Base64 allows no more than 76 characters per line
         // if the line length is greater 76, then insert a line break
         if(lineLength + 4 > 76)
         {
            rval.push_back('\r');
            rval.push_back('\n');
            lineLength = 0;
         }

         // update line length
         lineLength += 4;

         // add the group to the buffer
         rval.append(group, 4);
      }
   }

   return rval;
}

void Base64Codec::decode(const string& str, char** data, unsigned int& length)
{
   // point data at NULL and set length to 0
   *data = NULL;
   length = 0;

   // remove all white space
   char temp[str.length()];
   unsigned int len = 0;
   for(unsigned int i = 0; i < str.length(); i++)
   {
      if(str[i] != ' ' && str[i] != '\t' &&
         str[i] != '\r' && str[i] != '\n')
      {
         temp[len++] = str[i];
      }
   }
   temp[len] = 0;

   // make sure the string is at least 4 characters
   if(len > 3)
   {
      // get and check the number of groups, must be a multiple of 4
      unsigned int groups = len / 4;
      if(groups * 4 == len)
      {
         // get the number of pad characters
         unsigned int padChars = 0;
         if(temp[len - 2] == '=')
         {
            padChars = 2;
         }
         else if(temp[len - 1] == '=')
         {
            padChars = 1;
         }

         // calculate the decoded length, it should be the number of
         // groups * 3 - padBytes
         length = groups * 3 - padChars;

         // allocate space for the byte array
         *data = (char*)malloc(length);

         // decode all the groups
         char bytes[3];
         unsigned int dataIndex = 0;
         unsigned int strIndex = 0;
         for(unsigned int i = 0; i < groups; i++, strIndex += 4)
         {
            // copy the decoded bytes into the decoded buffer
            decodeGroup(temp + strIndex, bytes, len);
            memcpy((*data) + dataIndex, bytes, len);
            dataIndex += len;
         }
      }
   }
}
<|endoftext|>


<commit_before>#include "MyConditionalPrior.h"
#include "DNest4/code/DNest4.h"
#include <cmath>

using namespace DNest4;

MyConditionalPrior::MyConditionalPrior(double x_min, double x_max,
					                   double y_min, double y_max)
:x_min(x_min)
,x_max(x_max)
,y_min(y_min)
,y_max(y_max)
,scale(sqrt((x_max - x_min)*(y_max - y_min)))
{

}

void MyConditionalPrior::from_prior(RNG& rng)
{
    // A Cauchy distribution
    const DNest4::Cauchy cauchy(0.0, 5.0);

    // Truncate to (-50, 50)
    do
    {
        typical_flux = cauchy.generate(rng);
    }while(std::abs(typical_flux) >= 50.0);
    typical_flux = exp(typical_flux);

    dev_log_flux = 3.0*rng.rand();

    typical_radius = exp(log(0.1*scale) + 2.0*rng.randn());
	dev_log_radius = 3.0*rng.rand();
}

double MyConditionalPrior::perturb_hyperparameters(RNG& rng)
{
	double logH = 0.0;

    int which = rng.rand_int(4);

    if(which == 0)
    {
        // A Cauchy distribution
        const DNest4::Cauchy cauchy(0.0, 5.0);

        typical_flux = log(typical_flux);
        logH += cauchy.perturb(typical_flux, rng);
        if(std::abs(typical_flux) >= 50.0)
            return -1E300;
        typical_flux = exp(typical_flux);
    }
    else if(which == 1)
    {
        dev_log_flux += 3.0*rng.randh();
        DNest4::wrap(dev_log_flux, 0.0, 3.0);
    }
    else if(which == 2)
    {
        typical_radius = log(typical_radius);
        logH -= -0.5*pow((typical_radius - log(0.1*scale))/2.0, 2);
        typical_radius += 2.0*rng.randh();
        logH += -0.5*pow((typical_radius - log(0.1*scale))/2.0, 2);
        typical_radius = exp(typical_radius);
    }
    else if(which == 3)
    {
        dev_log_radius += 3.0*rng.randh();
        DNest4::wrap(dev_log_radius, 0.0, 3.0);
    }

	return logH;
}

// x, y, flux, radius, q, theta, rinner/router, Minner/Mtotal
double MyConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
	double logp = 0.0;

    // Position
    if(vec[0] < x_min || vec[0] > x_max || vec[1] < y_min || vec[1] > y_max)
        return -1E300;

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    logp += -log(vec[2]) + laplace1.log_pdf(log(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    logp += -log(vec[3]) + laplace2.log_pdf(log(vec[3]));

    // q
    if(vec[4] < 0.2 || vec[4] > 1.0)
        return -1E300;

    // theta
    if(vec[5] < 0.0 || vec[5] > 2*M_PI)
        return -1E300;

    // Radius ratio
    if(vec[6] < 0.0 || vec[6] > 1.0)
        return -1E300;

    // Mass fraction
    if(vec[7] < 0.0 || vec[7] > 1.0)
        return -1E300;

	return logp;
}

void MyConditionalPrior::from_uniform(std::vector<double>& vec) const
{
    // Position
    vec[0] = x_min + (x_max - x_min)*vec[0];
    vec[1] = y_min + (y_max - y_min)*vec[1];

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    vec[2] = exp(laplace1.cdf_inverse(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    vec[3] = exp(laplace2.cdf_inverse(vec[3]));

    // q
    vec[4] = 0.2 + 0.8*vec[4];

    // theta
    vec[5] = 2.0*M_PI*vec[5];

    // Radius ratio
    // No action needed

    // Mass fraction
    // No action needed
}

void MyConditionalPrior::to_uniform(std::vector<double>& vec) const
{
       // Position
    vec[0] = (vec[0] - x_min)/(x_max - x_min);
    vec[1] = (vec[1] - y_min)/(y_max - y_min);

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    vec[2] = laplace1.cdf(log(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    vec[3] = laplace2.cdf(log(vec[3]));

    // q
    vec[4] = (vec[4] - 0.2)/0.8;

    // theta
    vec[5] = vec[5]/(2.0*M_PI);

    // Radius ratio
    // No action needed

    // Mass fraction
    // No action needed
}

void MyConditionalPrior::print(std::ostream& out) const
{
    out << typical_flux << ' ' << dev_log_flux << ' ';
    out << typical_radius << ' ' << dev_log_radius << ' ';
}

<commit_msg>Fixed warning about tabs vs spaces<commit_after>#include "MyConditionalPrior.h"
#include "DNest4/code/DNest4.h"
#include <cmath>

using namespace DNest4;

MyConditionalPrior::MyConditionalPrior(double x_min, double x_max,
					                   double y_min, double y_max)
:x_min(x_min)
,x_max(x_max)
,y_min(y_min)
,y_max(y_max)
,scale(sqrt((x_max - x_min)*(y_max - y_min)))
{

}

void MyConditionalPrior::from_prior(RNG& rng)
{
    // A Cauchy distribution
    const DNest4::Cauchy cauchy(0.0, 5.0);

    // Truncate to (-50, 50)
    do
    {
        typical_flux = cauchy.generate(rng);
    }while(std::abs(typical_flux) >= 50.0);
    typical_flux = exp(typical_flux);

    dev_log_flux = 3.0*rng.rand();

    typical_radius = exp(log(0.1*scale) + 2.0*rng.randn());
	dev_log_radius = 3.0*rng.rand();
}

double MyConditionalPrior::perturb_hyperparameters(RNG& rng)
{
	double logH = 0.0;

    int which = rng.rand_int(4);

    if(which == 0)
    {
        // A Cauchy distribution
        const DNest4::Cauchy cauchy(0.0, 5.0);

        typical_flux = log(typical_flux);
        logH += cauchy.perturb(typical_flux, rng);
        if(std::abs(typical_flux) >= 50.0)
            return -1E300;
        typical_flux = exp(typical_flux);
    }
    else if(which == 1)
    {
        dev_log_flux += 3.0*rng.randh();
        DNest4::wrap(dev_log_flux, 0.0, 3.0);
    }
    else if(which == 2)
    {
        typical_radius = log(typical_radius);
        logH -= -0.5*pow((typical_radius - log(0.1*scale))/2.0, 2);
        typical_radius += 2.0*rng.randh();
        logH += -0.5*pow((typical_radius - log(0.1*scale))/2.0, 2);
        typical_radius = exp(typical_radius);
    }
    else if(which == 3)
    {
        dev_log_radius += 3.0*rng.randh();
        DNest4::wrap(dev_log_radius, 0.0, 3.0);
    }

	return logH;
}

// x, y, flux, radius, q, theta, rinner/router, Minner/Mtotal
double MyConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
    double logp = 0.0;

    // Position
    if(vec[0] < x_min || vec[0] > x_max || vec[1] < y_min || vec[1] > y_max)
        return -1E300;

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    logp += -log(vec[2]) + laplace1.log_pdf(log(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    logp += -log(vec[3]) + laplace2.log_pdf(log(vec[3]));

    // q
    if(vec[4] < 0.2 || vec[4] > 1.0)
        return -1E300;

    // theta
    if(vec[5] < 0.0 || vec[5] > 2*M_PI)
        return -1E300;

    // Radius ratio
    if(vec[6] < 0.0 || vec[6] > 1.0)
        return -1E300;

    // Mass fraction
    if(vec[7] < 0.0 || vec[7] > 1.0)
        return -1E300;

    return logp;
}

void MyConditionalPrior::from_uniform(std::vector<double>& vec) const
{
    // Position
    vec[0] = x_min + (x_max - x_min)*vec[0];
    vec[1] = y_min + (y_max - y_min)*vec[1];

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    vec[2] = exp(laplace1.cdf_inverse(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    vec[3] = exp(laplace2.cdf_inverse(vec[3]));

    // q
    vec[4] = 0.2 + 0.8*vec[4];

    // theta
    vec[5] = 2.0*M_PI*vec[5];

    // Radius ratio
    // No action needed

    // Mass fraction
    // No action needed
}

void MyConditionalPrior::to_uniform(std::vector<double>& vec) const
{
       // Position
    vec[0] = (vec[0] - x_min)/(x_max - x_min);
    vec[1] = (vec[1] - y_min)/(y_max - y_min);

    // Flux
    DNest4::Laplace laplace1(log(typical_flux), dev_log_flux);
    vec[2] = laplace1.cdf(log(vec[2]));

    // Radius
    DNest4::Laplace laplace2(log(typical_radius), dev_log_radius);
    vec[3] = laplace2.cdf(log(vec[3]));

    // q
    vec[4] = (vec[4] - 0.2)/0.8;

    // theta
    vec[5] = vec[5]/(2.0*M_PI);

    // Radius ratio
    // No action needed

    // Mass fraction
    // No action needed
}

void MyConditionalPrior::print(std::ostream& out) const
{
    out << typical_flux << ' ' << dev_log_flux << ' ';
    out << typical_radius << ' ' << dev_log_radius << ' ';
}

<|endoftext|>


<commit_before>/* kmail folder-list combo-box */
/* Author: Ronen Tzur <rtzur@shani.net> */

#include <config.h>

#include "kmfoldercombobox.h"
#include "kmfoldermgr.h"
#include "kmkernel.h"

//-----------------------------------------------------------------------------

KMFolderComboBox::KMFolderComboBox( QWidget *parent, char *name )
  : QComboBox( parent, name )
{
  init();
}

//-----------------------------------------------------------------------------

KMFolderComboBox::KMFolderComboBox( bool rw, QWidget *parent, char *name )
  : QComboBox( rw, parent, name )
{
  init();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::init()
{
  mSpecialIdx = -1;
  mOutboxShown = true;
  mImapShown = true;
  refreshFolders();
  connect( this, SIGNAL( activated(int) ),
      this, SLOT( slotActivated(int) ) );
  connect( kmkernel->folderMgr(), SIGNAL(changed()),
      this, SLOT(refreshFolders()) );
  connect( kmkernel->dimapFolderMgr(), SIGNAL(changed()),
      this, SLOT(refreshFolders()) );
  if (mImapShown)
    connect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::showOutboxFolder(bool shown)
{
  mOutboxShown = shown;
  refreshFolders();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::showImapFolders(bool shown)
{
  mImapShown = shown;
  refreshFolders();
  if (shown)
    connect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
  else
    disconnect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::createFolderList(QStringList *names,
                                        QValueList<QGuardedPtr<KMFolder> > *folders)
{
  if (mImapShown)
    kmkernel->imapFolderMgr()->createI18nFolderList( names, folders );

  kmkernel->dimapFolderMgr()->createI18nFolderList( names, folders );
  kmkernel->folderMgr()->createFolderList( names, folders );
  uint i = 0;
  while (i < folders->count())
  {
    if ((*(folders->at(i)))->isSystemFolder()
	&& (*(folders->at(i)))->folderType() != KMFolderTypeImap
	&& (*(folders->at(i)))->folderType() != KMFolderTypeCachedImap)
    {
      folders->remove(folders->at(i));
      names->remove(names->at(i));
    }
    else i++;
  }

  folders->prepend(kmkernel->draftsFolder());
  folders->prepend(kmkernel->trashFolder());
  folders->prepend(kmkernel->sentFolder());
  if (mOutboxShown) folders->prepend(kmkernel->outboxFolder());
  folders->prepend(kmkernel->inboxFolder());
  for (int i = ((mOutboxShown) ? 4 : 3); i >= 0; i--)
    names->prepend((*(folders->at(i)))->label());
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::refreshFolders()
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  KMFolder *folder = getFolder();
  this->clear();
  insertStringList( names );
  setFolder( folder );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::setFolder( KMFolder *aFolder )
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  int idx = folders.findIndex( aFolder );
  if (idx == -1)
    idx = folders.findIndex( kmkernel->draftsFolder() );
  setCurrentItem( idx >= 0 ? idx : 0 );

  mFolder = aFolder;
}

void KMFolderComboBox::setFolder( const QString &idString )
{
  KMFolder * folder = kmkernel->findFolderById( idString );
  if (!folder && !idString.isEmpty())
  {
     if (mSpecialIdx >= 0)
        removeItem(mSpecialIdx);
     mSpecialIdx = count();
     insertItem(idString, -1);
     setCurrentItem(mSpecialIdx);

     mFolder = 0;
     return;
  }
  setFolder( folder );
}

//-----------------------------------------------------------------------------

KMFolder *KMFolderComboBox::getFolder()
{
  if (mFolder)
    return mFolder;

  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  if (currentItem() == mSpecialIdx)
     return 0;

  QString text = currentText();
  int idx = 0;
  QStringList::Iterator it;
  for ( it = names.begin(); it != names.end(); ++it ) {
    if ( ! (*it).compare( text ) )
      return *folders.at( idx );
    idx++;
  }

  return kmkernel->draftsFolder();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::slotActivated(int index)
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  if (index == mSpecialIdx)
  {
     mFolder = 0;
  }
  else
  {
     mFolder = *folders.at( index );
  }
}

//-----------------------------------------------------------------------------

#include "kmfoldercombobox.moc"
<commit_msg>Forward port of CVS commit by kloecker:<commit_after>/* kmail folder-list combo-box */
/* Author: Ronen Tzur <rtzur@shani.net> */

#include <config.h>

#include "kmfoldercombobox.h"
#include "kmfoldermgr.h"
#include "kmkernel.h"

//-----------------------------------------------------------------------------

KMFolderComboBox::KMFolderComboBox( QWidget *parent, char *name )
  : QComboBox( parent, name )
{
  init();
}

//-----------------------------------------------------------------------------

KMFolderComboBox::KMFolderComboBox( bool rw, QWidget *parent, char *name )
  : QComboBox( rw, parent, name )
{
  init();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::init()
{
  mSpecialIdx = -1;
  mOutboxShown = true;
  mImapShown = true;
  refreshFolders();
  connect( this, SIGNAL( activated(int) ),
      this, SLOT( slotActivated(int) ) );
  connect( kmkernel->folderMgr(), SIGNAL(changed()),
      this, SLOT(refreshFolders()) );
  connect( kmkernel->dimapFolderMgr(), SIGNAL(changed()),
      this, SLOT(refreshFolders()) );
  if (mImapShown)
    connect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::showOutboxFolder(bool shown)
{
  mOutboxShown = shown;
  refreshFolders();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::showImapFolders(bool shown)
{
  mImapShown = shown;
  refreshFolders();
  if (shown)
    connect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
  else
    disconnect( kmkernel->imapFolderMgr(), SIGNAL(changed()),
        this, SLOT(refreshFolders()) );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::createFolderList(QStringList *names,
                                        QValueList<QGuardedPtr<KMFolder> > *folders)
{
  kmkernel->folderMgr()->createI18nFolderList( names, folders );
  if ( !mOutboxShown ) {
    QValueList< QGuardedPtr<KMFolder> >::iterator folderIt = folders->begin();
    QStringList::iterator namesIt = names->begin();
    for ( ; folderIt != folders->end(); ++folderIt, ++namesIt ) {
      KMFolder *folder = *folderIt;
      if ( folder == kmkernel->outboxFolder() )
        break;
    }
    if ( folderIt != folders->end() ) {
      folders->remove( folderIt );
      names->remove( namesIt );
    }
  }

  if (mImapShown)
    kmkernel->imapFolderMgr()->createI18nFolderList( names, folders );

  kmkernel->dimapFolderMgr()->createI18nFolderList( names, folders );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::refreshFolders()
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  KMFolder *folder = getFolder();
  this->clear();
  insertStringList( names );
  setFolder( folder );
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::setFolder( KMFolder *aFolder )
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  int idx = folders.findIndex( aFolder );
  if (idx == -1)
    idx = folders.findIndex( kmkernel->draftsFolder() );
  setCurrentItem( idx >= 0 ? idx : 0 );

  mFolder = aFolder;
}

void KMFolderComboBox::setFolder( const QString &idString )
{
  KMFolder * folder = kmkernel->findFolderById( idString );
  if (!folder && !idString.isEmpty())
  {
     if (mSpecialIdx >= 0)
        removeItem(mSpecialIdx);
     mSpecialIdx = count();
     insertItem(idString, -1);
     setCurrentItem(mSpecialIdx);

     mFolder = 0;
     return;
  }
  setFolder( folder );
}

//-----------------------------------------------------------------------------

KMFolder *KMFolderComboBox::getFolder()
{
  if (mFolder)
    return mFolder;

  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  if (currentItem() == mSpecialIdx)
     return 0;

  QString text = currentText();
  int idx = 0;
  QStringList::Iterator it;
  for ( it = names.begin(); it != names.end(); ++it ) {
    if ( ! (*it).compare( text ) )
      return *folders.at( idx );
    idx++;
  }

  return kmkernel->draftsFolder();
}

//-----------------------------------------------------------------------------

void KMFolderComboBox::slotActivated(int index)
{
  QStringList names;
  QValueList<QGuardedPtr<KMFolder> > folders;
  createFolderList( &names, &folders );

  if (index == mSpecialIdx)
  {
     mFolder = 0;
  }
  else
  {
     mFolder = *folders.at( index );
  }
}

//-----------------------------------------------------------------------------

#include "kmfoldercombobox.moc"
<|endoftext|>


<commit_before>#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <strsafe.h>

#define BUFSIZE 512

int _tmain(int argc, TCHAR *argv[])
{
	_tprintf(TEXT("Client is started!\n\n"));

	HANDLE hPipe = INVALID_HANDLE_VALUE; // Идентификатор канала
	LPTSTR lpszPipename = TEXT("\\\\192.168.124.235\\pipe\\$$MyPipe$$"); // Имя создаваемого канала Pipe
	TCHAR chBuf[BUFSIZE]; // Буфер для передачи данных через канал
	DWORD readbytes, writebytes; // Число байт прочитанных и переданных

	// Создание SECURITY_ATTRIBUTES и SECURITY_DESCRIPTOR объектов
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	// Инициализация SECURITY_DESCRIPTOR значениями по-умолчанию
	if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) == 0)
	{
		_tprintf(TEXT("InitializeSecurityDescriptor failed with error %d\n"), GetLastError());
		_getch();
		return -1;
	}
	// Установка поля DACL в SECURITY_DESCRIPTOR в NULL
	if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE) == 0)
	{
		_tprintf(TEXT("SetSecurityDescriptorDacl failed with error %d\n"), GetLastError());
		_getch();
		return -1;
	}
	// Установка SECURITY_DESCRIPTOR в структуре SECURITY_ATTRIBUTES
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = &sd;
	sa.bInheritHandle = FALSE; //запрещение наследования

	_tprintf(TEXT("Try to use WaitNamedPipe...\n"));
	// Пытаемся открыть именованный канал, если надо - ожидаем его освобождения
	while (1)
	{
		// Создаем канал с процессом-сервером:
		hPipe = CreateFile(
			lpszPipename, // имя канала,
			GENERIC_READ // текущий клиент имеет доступ на чтение,
			| GENERIC_WRITE, // текущий клиент имеет доступ на запись,
			0, // тип доступа,
			&sa, // атрибуты защиты,
			OPEN_EXISTING, // открывается существующий файл,
			0, // атрибуты и флаги для файла,
			NULL); // доступа к файлу шаблона.

		// Продолжаем работу, если канал создать удалось
		if (hPipe != INVALID_HANDLE_VALUE)
			break;

		// Выход, если ошибка связана не с занятым каналом.
		if (GetLastError() != ERROR_PIPE_BUSY)
		{
			_tprintf(TEXT("Could not open pipe. GLE=%d\n"), GetLastError());
			_getch();
			return -1;
		}

		// Если все каналы заняты, ждём 20 секунд
		if (!WaitNamedPipe(lpszPipename, 20000))
		{
			_tprintf(TEXT("Could not open pipe: 20 second wait timed out."));
			_getch();
			return -1;
		}
	}

	// Выводим сообщение о создании канала
	_tprintf(TEXT("Successfully connected!\n\nInput message...\n"));
	// Цикл обмена данными с серверным процессом
	while (1)
	{
		// Выводим приглашение для ввода команды
		_tprintf(TEXT("cmd>"));
		// Вводим текстовую строку
		_fgetts(chBuf, BUFSIZE, stdin);
		// Передаем введенную строку серверному процессу в качестве команды
		if (!WriteFile(hPipe, chBuf, (lstrlen(chBuf) + 1)*sizeof(TCHAR), &writebytes, NULL))
		{
			_tprintf(TEXT("connection refused\n"));
			break;
		}
		// Получаем эту же команду обратно от сервера
		if (ReadFile(hPipe, chBuf, BUFSIZE*sizeof(TCHAR), &readbytes, NULL))
			_tprintf(TEXT("Received from server: %s\n"), chBuf);
		// Если произошла ошибка, выводим ее код и завершаем работу приложения
		else {
			_tprintf(TEXT("ReadFile: Error %ld\n"), GetLastError());
			_getch();
			break;
		}
		// В ответ на команду "exit" завершаем цикл обмена данными с серверным процессом
		if (!_tcsncmp(chBuf, L"exit", 4))
			break;
	}

	// Закрываем идентификатор канала
	CloseHandle(hPipe);

	_tprintf(TEXT("Press ENTER to terminate connection and exit\n"));
	_getch();
	return 0;
}<commit_msg>[fix] NamedPipeNetworkClient is restored.<commit_after>#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <strsafe.h>
#include "logger.h"

#define BUFSIZE 512

int _tmain(int argc, _TCHAR* argv[]) {
	//Init log
	initlog(argv[0]);
	_tprintf(_T("Client is started!\n\n"));

	HANDLE hPipe = INVALID_HANDLE_VALUE; // Идентификатор канала
	LPTSTR lpszPipename = TEXT("\\\\192.168.124.235\\pipe\\$$MyPipe$$"); // Имя создаваемого канала Pipe
	_TCHAR chBuf[BUFSIZE]; // Буфер для передачи данных через канал
	DWORD readbytes, writebytes; // Число байт прочитанных и переданных

	// Создание SECURITY_ATTRIBUTES и SECURITY_DESCRIPTOR объектов
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	// Инициализация SECURITY_DESCRIPTOR значениями по-умолчанию
	if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) == 0) {
		double errorcode = GetLastError();
		writelog(_T("InitializeSecurityDescriptor failed, GLE = %d"), errorcode);
		_tprintf(_T("InitializeSecurityDescriptor failed, GLE = %d\n"), errorcode);
		closelog();
		exit(2);
	}
	// Установка поля DACL в SECURITY_DESCRIPTOR в NULL
	if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE) == 0)	{
		double errorcode = GetLastError();
		writelog(_T("SetSecurityDescriptorDacl failed, GLE = %d"), errorcode);
		_tprintf(_T("SetSecurityDescriptorDacl failed, GLE = %d\n"), errorcode);
		closelog();
		exit(3);
	}
	// Установка SECURITY_DESCRIPTOR в структуре SECURITY_ATTRIBUTES
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = &sd;
	sa.bInheritHandle = FALSE; //запрещение наследования

	writelog(_T("Try to use WaitNamedPipe..."));
	_tprintf(_T("Try to use WaitNamedPipe...\n"));
	// Пытаемся открыть именованный канал, если надо - ожидаем его освобождения
	while (1)
	{
		// Создаем канал с процессом-сервером:
		hPipe = CreateFile(
			lpszPipename, // имя канала,
			GENERIC_READ // текущий клиент имеет доступ на чтение,
			| GENERIC_WRITE, // текущий клиент имеет доступ на запись,
			0, // тип доступа,
			&sa, // атрибуты защиты,
			OPEN_EXISTING, // открывается существующий файл,
			0, // атрибуты и флаги для файла,
			NULL); // доступа к файлу шаблона.

		// Продолжаем работу, если канал создать удалось
		if (hPipe != INVALID_HANDLE_VALUE)
			break;

		// Выход, если ошибка связана не с занятым каналом.
		if (GetLastError() != ERROR_PIPE_BUSY) {
			double errorcode = GetLastError();
			writelog(_T("Could not open pipe, GLE = %d"), errorcode);
			_tprintf(_T("Could not open pipe, GLE = %d\n"), errorcode);
			closelog();
			exit(4);
		}

		// Если все каналы заняты, ждём 20 секунд
		if (!WaitNamedPipe(lpszPipename, 20000)) {
			double errorcode = GetLastError();
			writelog(_T("Could not open pipe: 20 second wait timed out, GLE = %d"), errorcode);
			_tprintf(_T("ould not open pipe: 20 second wait timed out, GLE = %d\n"), errorcode);
			closelog();
			exit(5);
		}
	}

	// Выводим сообщение о создании канала
	writelog(_T("Successfully connected"));
	_tprintf(_T("Successfully connected!\n\nInput message...\n"));
	// Цикл обмена данными с серверным процессом
	while (1)
	{
		// Выводим приглашение для ввода команды
		_tprintf(TEXT("cmd>"));
		// Вводим текстовую строку
		_fgetts(chBuf, BUFSIZE, stdin);
		writelog(_T("Inpust string is %s"), chBuf);
		// Передаем введенную строку серверному процессу в качестве команды
		if (!WriteFile(hPipe, chBuf, (lstrlen(chBuf) + 1)*sizeof(TCHAR), &writebytes, NULL)) {
			double errorcode = GetLastError();
			writelog(_T("Connection refused, GLE = %d"), errorcode);
			_tprintf(_T("Connection refused, GLE = %d\n"), errorcode);
			break;
		}
		// Получаем эту же команду обратно от сервера
		if (ReadFile(hPipe, chBuf, BUFSIZE*sizeof(TCHAR), &readbytes, NULL)) {
			writelog(_T("Received from server: %s\n"), chBuf);
			_tprintf(_T("Received from server: %s\n"), chBuf);
		}
		// Если произошла ошибка, выводим ее код и завершаем работу приложения
		else {
			double errorcode = GetLastError();
			writelog(_T("ReadFile: Error %ld"), errorcode);
			_tprintf(_T("ReadFile: Error %ld\n"), errorcode);
			break;
		}
		// В ответ на команду "exit" завершаем цикл обмена данными с серверным процессом
		if (!_tcsncmp(chBuf, L"exit", 4))
			break;
	}

	// Закрываем идентификатор канала
	CloseHandle(hPipe);

	closelog();
	_tprintf(TEXT("Press ENTER to terminate connection and exit\n"));
	_getch();
	return 0;
}<|endoftext|>