<commit_before>#include "videosourcefactory.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#endif
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
#ifdef USE_BLACKMAGICSDK
#include "blackmagicsdk_video_source.h"
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_source.h"
#endif

namespace gg
{

VideoSourceFactory VideoSourceFactory::_factory_singleton;

VideoSourceFactory::VideoSourceFactory()
{
    for (size_t i = 0; i < NUM_DEVICES; i++)
        _devices[i] = nullptr;
}

VideoSourceFactory::~VideoSourceFactory()
{
    free_device(DVI2PCIeDuo_DVI);
    free_device(DVI2PCIeDuo_SDI);
}

VideoSourceFactory & VideoSourceFactory::get_instance()
{
    return _factory_singleton;
}

IVideoSource * VideoSourceFactory::get_device(Device device,
                                              ColourSpace colour)
{
    // if already connected, return
    if (_devices[(int) device] != nullptr)
    {
        if (_device_colours[(int) device] != colour)
            throw DeviceAlreadyConnected(
                "Device already connected using another colour space"
            );
        else
            return _devices[(int) device];
    }

    // otherwise, connect
    IVideoSource * src = nullptr;
    switch (device)
    {

    // Epiphan DVI2PCIe Duo DVI ========================================
    case DVI2PCIeDuo_DVI:
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
#ifdef USE_OPENCV
            src = new VideoSourceOpenCV(0);
#else
            throw VideoSourceError(
                "BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
            break;

        // I420 ========================================
        case I420:
#ifdef USE_LIBVLC
            try
            {
                src = new VideoSourceVLC("v4l2:///dev/video0:chroma=I420", 60);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_DVI
            try
            {
                src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_DVI,
                                                V2U_GRABFRAME_FORMAT_I420);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#else
            throw DeviceNotFound("Epiphan_DVI2PCIeDuo_DVI macro not defined");
#endif
#else
            throw VideoSourceError(
                "I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
            break;

        // unsupported colour space ========================================
        default:
            throw VideoSourceError("Colour space not supported");
        }
        break;

    // Epiphan DVI2PCIe Duo SDI ========================================
    case DVI2PCIeDuo_SDI:
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
#ifdef USE_OPENCV
            src = new VideoSourceOpenCV(1);
#else
            throw VideoSourceError(
                "BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
            break;

        // I420 ========================================
        case I420:
#ifdef USE_LIBVLC
            try
            {
                src = new VideoSourceVLC("v4l2:///dev/video1:chroma=I420", 60);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_SDI
            try
            {
                src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_SDI,
                                                V2U_GRABFRAME_FORMAT_I420);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#else
            throw DeviceNotFound("Epiphan_DVI2PCIeDuo_SDI macro not defined");
#endif
#else
            throw VideoSourceError(
                "I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
            break;

        // unsupported colour space ========================================
        default:
            throw VideoSourceError("Colour space not supported");
        }
        break;

    // Blackmagic DeckLink SDI 4K ========================================
    case DeckLinkSDI4K:
#ifdef USE_BLACKMAGICSDK
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
        // UYVY ========================================
        case UYVY:
            break;

        // I420 ========================================
        case I420:
        default:
            throw VideoSourceError("Colour space not supported for"
                                   " Blackmagic DeckLink SDI 4K");
        }
        src = new VideoSourceBlackmagicSDK(0, colour);
#else
        throw VideoSourceError(
            "Blackmagic DeckLink SDI 4K supported only through"
            " Blackmagic Desktop Video SDK");
#endif
        break;

    // unsupported device ========================================
    default:
        std::string msg;
        msg.append("Device ")
           .append(std::to_string(device))
           .append(" not recognised");
        throw DeviceNotFound(msg);
    }

    if (src != nullptr)
    {
        // check querying frame dimensions
        int width = -1, height = -1;
        if (not src->get_frame_dimensions(width, height))
        {
            throw DeviceOffline(
                "Device connected but does not return frame dimensions");
        }

        // check meaningful frame dimensions
        if (width <= 0 or height <= 0)
        {
            throw DeviceOffline(
                "Device connected but returns meaningless frame dimensions");
        }

        // check querying frames
        VideoFrame frame(colour, true);
        if (not src->get_frame(frame))
        {
            throw DeviceOffline(
                "Device connected does not return frames");
        }

        // if no exception raised up to here, glory be to GIFT-Grab
        _devices[(int) device] = src;
        _device_colours[(int) device] = colour;
    }

    return _devices[(int) device];
}

void VideoSourceFactory::free_device(Device device)
{
    switch (device)
    {
    case DVI2PCIeDuo_DVI:
    case DVI2PCIeDuo_SDI:
    case DeckLinkSDI4K:
        break; // everything up to here is recognised
    default:
        std::string msg;
        msg.append("Device ")
           .append(std::to_string(device))
           .append(" not recognised");
        throw DeviceNotFound(msg);
    }

    if (_devices[(int) device] != nullptr)
        delete _devices[(int) device];
    _devices[(int) device] = nullptr;
}

IVideoSource * VideoSourceFactory::connect_network_source(
        std::string address, enum ColourSpace colour)
{
    IVideoSource * source = nullptr;
    switch (colour)
    {
    case I420:
#ifdef USE_LIBVLC
        try
        {
            source = new gg::VideoSourceVLC(address);
        }
        catch (VideoSourceError & e)
        {
            throw NetworkSourceUnavailable(e.what());
        }
#else
        throw VideoSourceError(
            "I420 colour space on network sources supported only with libVLC"
        );
#endif
        break;
    case BGRA:
#ifdef USE_OPENCV
        try
        {
            source = new VideoSourceOpenCV(address.c_str());
        }
        catch (VideoSourceError & e)
        {
            throw NetworkSourceUnavailable(e.what());
        }
        break;
#else
        throw VideoSourceError(
            "BGRA colour space on network sources supported only with OpenCV"
        );
#endif
    }

    return source;
}

IVideoSource * VideoSourceFactory::create_file_reader(
        const std::string filepath,
        enum Codec codec,
        enum ColourSpace colour_space)
{
    std::string codec_str = "", colour_space_str = "";
    switch(codec)
    {
    case Xvid:
        codec_str = "Xvid";
        break;
    case HEVC:
        codec_str = "HEVC";
        break;
    case VP9:
        codec_str = "VP9";
        break;
    default:
        throw VideoSourceError("Codec not supported");
    }
    switch(colour_space)
    {
    case BGRA:
        colour_space_str = "BGRA";
        break;
    case I420:
        colour_space_str = "I420";
        break;
    case UYVY:
        colour_space_str = "UYVY";
        break;
    default:
        throw VideoSourceError("Colour space not supported");
    }

#ifdef USE_FFMPEG
    return new VideoSourceFFmpeg(filepath, colour_space);
#else
    std::string error_msg = "";
    error_msg.append("Reading ").append(codec_str)
             .append(" files in ").append(colour_space_str)
             .append(" colour space supported only")
             .append(" with FFmpeg");
    throw VideoSourceError(error_msg);
#endif
}

}
<commit_msg>Issue #74: simplified create_file_reader function, as now only FFmpeg required for file readers<commit_after>#include "videosourcefactory.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#endif
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
#ifdef USE_BLACKMAGICSDK
#include "blackmagicsdk_video_source.h"
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_source.h"
#endif

namespace gg
{

VideoSourceFactory VideoSourceFactory::_factory_singleton;

VideoSourceFactory::VideoSourceFactory()
{
    for (size_t i = 0; i < NUM_DEVICES; i++)
        _devices[i] = nullptr;
}

VideoSourceFactory::~VideoSourceFactory()
{
    free_device(DVI2PCIeDuo_DVI);
    free_device(DVI2PCIeDuo_SDI);
}

VideoSourceFactory & VideoSourceFactory::get_instance()
{
    return _factory_singleton;
}

IVideoSource * VideoSourceFactory::get_device(Device device,
                                              ColourSpace colour)
{
    // if already connected, return
    if (_devices[(int) device] != nullptr)
    {
        if (_device_colours[(int) device] != colour)
            throw DeviceAlreadyConnected(
                "Device already connected using another colour space"
            );
        else
            return _devices[(int) device];
    }

    // otherwise, connect
    IVideoSource * src = nullptr;
    switch (device)
    {

    // Epiphan DVI2PCIe Duo DVI ========================================
    case DVI2PCIeDuo_DVI:
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
#ifdef USE_OPENCV
            src = new VideoSourceOpenCV(0);
#else
            throw VideoSourceError(
                "BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
            break;

        // I420 ========================================
        case I420:
#ifdef USE_LIBVLC
            try
            {
                src = new VideoSourceVLC("v4l2:///dev/video0:chroma=I420", 60);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_DVI
            try
            {
                src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_DVI,
                                                V2U_GRABFRAME_FORMAT_I420);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#else
            throw DeviceNotFound("Epiphan_DVI2PCIeDuo_DVI macro not defined");
#endif
#else
            throw VideoSourceError(
                "I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
            break;

        // unsupported colour space ========================================
        default:
            throw VideoSourceError("Colour space not supported");
        }
        break;

    // Epiphan DVI2PCIe Duo SDI ========================================
    case DVI2PCIeDuo_SDI:
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
#ifdef USE_OPENCV
            src = new VideoSourceOpenCV(1);
#else
            throw VideoSourceError(
                "BGRA colour space on Epiphan DVI2PCIe Duo supported only with OpenCV");
#endif
            break;

        // I420 ========================================
        case I420:
#ifdef USE_LIBVLC
            try
            {
                src = new VideoSourceVLC("v4l2:///dev/video1:chroma=I420", 60);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#elif defined(USE_EPIPHANSDK)
#ifdef Epiphan_DVI2PCIeDuo_SDI
            try
            {
                src = new VideoSourceEpiphanSDK(Epiphan_DVI2PCIeDuo_SDI,
                                                V2U_GRABFRAME_FORMAT_I420);
            }
            catch (VideoSourceError & e)
            {
                throw DeviceNotFound(e.what());
            }
#else
            throw DeviceNotFound("Epiphan_DVI2PCIeDuo_SDI macro not defined");
#endif
#else
            throw VideoSourceError(
                "I420 colour space on Epiphan DVI2PCIe Duo supported only with Epiphan SDK or libVLC");
#endif
            break;

        // unsupported colour space ========================================
        default:
            throw VideoSourceError("Colour space not supported");
        }
        break;

    // Blackmagic DeckLink SDI 4K ========================================
    case DeckLinkSDI4K:
#ifdef USE_BLACKMAGICSDK
        switch (colour)
        {

        // BGRA ========================================
        case BGRA:
        // UYVY ========================================
        case UYVY:
            break;

        // I420 ========================================
        case I420:
        default:
            throw VideoSourceError("Colour space not supported for"
                                   " Blackmagic DeckLink SDI 4K");
        }
        src = new VideoSourceBlackmagicSDK(0, colour);
#else
        throw VideoSourceError(
            "Blackmagic DeckLink SDI 4K supported only through"
            " Blackmagic Desktop Video SDK");
#endif
        break;

    // unsupported device ========================================
    default:
        std::string msg;
        msg.append("Device ")
           .append(std::to_string(device))
           .append(" not recognised");
        throw DeviceNotFound(msg);
    }

    if (src != nullptr)
    {
        // check querying frame dimensions
        int width = -1, height = -1;
        if (not src->get_frame_dimensions(width, height))
        {
            throw DeviceOffline(
                "Device connected but does not return frame dimensions");
        }

        // check meaningful frame dimensions
        if (width <= 0 or height <= 0)
        {
            throw DeviceOffline(
                "Device connected but returns meaningless frame dimensions");
        }

        // check querying frames
        VideoFrame frame(colour, true);
        if (not src->get_frame(frame))
        {
            throw DeviceOffline(
                "Device connected does not return frames");
        }

        // if no exception raised up to here, glory be to GIFT-Grab
        _devices[(int) device] = src;
        _device_colours[(int) device] = colour;
    }

    return _devices[(int) device];
}

void VideoSourceFactory::free_device(Device device)
{
    switch (device)
    {
    case DVI2PCIeDuo_DVI:
    case DVI2PCIeDuo_SDI:
    case DeckLinkSDI4K:
        break; // everything up to here is recognised
    default:
        std::string msg;
        msg.append("Device ")
           .append(std::to_string(device))
           .append(" not recognised");
        throw DeviceNotFound(msg);
    }

    if (_devices[(int) device] != nullptr)
        delete _devices[(int) device];
    _devices[(int) device] = nullptr;
}

IVideoSource * VideoSourceFactory::connect_network_source(
        std::string address, enum ColourSpace colour)
{
    IVideoSource * source = nullptr;
    switch (colour)
    {
    case I420:
#ifdef USE_LIBVLC
        try
        {
            source = new gg::VideoSourceVLC(address);
        }
        catch (VideoSourceError & e)
        {
            throw NetworkSourceUnavailable(e.what());
        }
#else
        throw VideoSourceError(
            "I420 colour space on network sources supported only with libVLC"
        );
#endif
        break;
    case BGRA:
#ifdef USE_OPENCV
        try
        {
            source = new VideoSourceOpenCV(address.c_str());
        }
        catch (VideoSourceError & e)
        {
            throw NetworkSourceUnavailable(e.what());
        }
        break;
#else
        throw VideoSourceError(
            "BGRA colour space on network sources supported only with OpenCV"
        );
#endif
    }

    return source;
}

IVideoSource * VideoSourceFactory::create_file_reader(
        const std::string filepath,
        enum Codec codec,
        enum ColourSpace colour_space)
{
#ifdef USE_FFMPEG
    return new VideoSourceFFmpeg(filepath, colour_space);
#else
    throw VideoSourceError("Reading video files supported only"
                           " with FFmpeg");
#endif
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/login_prompt.h"

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "net/url_request/url_request.h"

using webkit_glue::PasswordForm;

// ----------------------------------------------------------------------------
// LoginHandlerGtk

// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerGtk : public LoginHandler,
                        public base::RefCountedThreadSafe<LoginHandlerGtk>,
                        public ConstrainedWindowGtkDelegate {
 public:
  LoginHandlerGtk(URLRequest* request, MessageLoop* ui_loop)
      : handled_auth_(false),
        dialog_(NULL),
        ui_loop_(ui_loop),
        request_(request),
        request_loop_(MessageLoop::current()),
        password_manager_(NULL) {
    DCHECK(request_) << "LoginHandlerGtk constructed with NULL request";

    AddRef();  // matched by ReleaseLater.
    if (!ResourceDispatcherHost::RenderViewForRequest(request_,
                                                      &render_process_host_id_,
                                                      &tab_contents_id_)) {
      NOTREACHED();
    }
  }

  virtual ~LoginHandlerGtk() {
    root_.Destroy();
  }

  // LoginHandler:
  virtual void BuildViewForPasswordManager(PasswordManager* manager,
                                           std::wstring explanation) {
    DCHECK(MessageLoop::current() == ui_loop_);

    root_.Own(gtk_vbox_new(NULL, gtk_util::kContentAreaBorder));
    GtkWidget* label = gtk_label_new(WideToUTF8(explanation).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(root_.get()), label, FALSE, FALSE, 0);

    username_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);

    password_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);
    gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);

    GtkWidget* table = gtk_util::CreateLabeledControlsGroup(
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_USERNAME_FIELD).c_str(),
        username_entry_,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_PASSWORD_FIELD).c_str(),
        password_entry_,
        NULL);
    gtk_box_pack_start(GTK_BOX(root_.get()), table, FALSE, FALSE, 0);

    GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
    gtk_box_pack_start(GTK_BOX(root_.get()), hbox, FALSE, FALSE, 0);

    GtkWidget* ok = gtk_button_new_from_stock(GTK_STOCK_OK);
    gtk_button_set_label(
        GTK_BUTTON(ok),
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL).c_str());
    g_signal_connect(ok, "clicked", G_CALLBACK(OnOKClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), ok, FALSE, FALSE, 0);

    GtkWidget* cancel = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
    g_signal_connect(cancel, "clicked", G_CALLBACK(OnCancelClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), cancel, FALSE, FALSE, 0);

    // Scary thread safety note: This can potentially be called *after* SetAuth
    // or CancelAuth (say, if the request was cancelled before the UI thread got
    // control).  However, that's OK since any UI interaction in those functions
    // will occur via an InvokeLater on the UI thread, which is guaranteed
    // to happen after this is called (since this was InvokeLater'd first).
    dialog_ = GetTabContentsForLogin()->CreateConstrainedDialog(this);

    // Now that we have attached ourself to the window, we can make our OK
    // button the default action and mess with the focus.
    GTK_WIDGET_SET_FLAGS(ok, GTK_CAN_DEFAULT);
    gtk_widget_grab_default(ok);
    gtk_widget_grab_focus(username_entry_);

    SendNotifications();
  }

  virtual void SetPasswordForm(const webkit_glue::PasswordForm& form) {
    password_form_ = form;
  }

  virtual void SetPasswordManager(PasswordManager* password_manager) {
    password_manager_ = password_manager;
  }

  virtual TabContents* GetTabContentsForLogin() {
    DCHECK(MessageLoop::current() == ui_loop_);

    return tab_util::GetTabContentsByID(render_process_host_id_,
                                        tab_contents_id_);
  }

  virtual void SetAuth(const std::wstring& username,
                       const std::wstring& password) {
    if (WasAuthHandled(true))
      return;

    // Tell the password manager the credentials were submitted / accepted.
    if (password_manager_) {
      password_form_.username_value = username;
      password_form_.password_value = password;
      password_manager_->ProvisionallySavePassword(password_form_);
    }

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SetAuthDeferred, username, password));
  }

  virtual void CancelAuth() {
    if (WasAuthHandled(true))
      return;

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CancelAuthDeferred));
  }

  virtual void OnRequestCancelled() {
    DCHECK(MessageLoop::current() == request_loop_) <<
        "Why is OnRequestCancelled called from the UI thread?";

    // Reference is no longer valid.
    request_ = NULL;

    // Give up on auth if the request was cancelled.
    CancelAuth();
  }

  // Overridden from ConstrainedWindowGtkDelegate:
  virtual GtkWidget* GetWidgetRoot() {
    return root_.get();
  }

  virtual void DeleteDelegate() {
    if (!WasAuthHandled(true)) {
      request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &LoginHandlerGtk::CancelAuthDeferred));
      SendNotifications();
    }

    // Delete this object once all InvokeLaters have been called.
    request_loop_->ReleaseSoon(FROM_HERE, this);
  }

 private:
  friend class LoginPrompt;

  // Calls SetAuth from the request_loop.
  void SetAuthDeferred(const std::wstring& username,
                       const std::wstring& password) {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->SetAuth(username, password);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Calls CancelAuth from the request_loop.
  void CancelAuthDeferred() {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->CancelAuth();
      // Verify that CancelAuth does destroy the request via our delegate.
      DCHECK(request_ != NULL);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Closes the view_contents from the UI loop.
  void CloseContentsDeferred() {
    DCHECK(MessageLoop::current() == ui_loop_);

    // The hosting ConstrainedWindow may have been freed.
    if (dialog_)
      dialog_->CloseConstrainedWindow();
  }

  // Returns whether authentication had been handled (SetAuth or CancelAuth).
  // If |set_handled| is true, it will mark authentication as handled.
  bool WasAuthHandled(bool set_handled) {
    AutoLock lock(handled_auth_lock_);
    bool was_handled = handled_auth_;
    if (set_handled)
      handled_auth_ = true;
    return was_handled;
  }

  // Notify observers that authentication is needed or received.  The automation
  // proxy uses this for testing.
  void SendNotifications() {
    DCHECK(MessageLoop::current() == ui_loop_);

    NotificationService* service = NotificationService::current();
    TabContents* requesting_contents = GetTabContentsForLogin();
    if (!requesting_contents)
      return;

    NavigationController* controller = &requesting_contents->controller();

    if (!WasAuthHandled(false)) {
      LoginNotificationDetails details(this);
      service->Notify(NotificationType::AUTH_NEEDED,
                      Source<NavigationController>(controller),
                      Details<LoginNotificationDetails>(&details));
    } else {
      service->Notify(NotificationType::AUTH_SUPPLIED,
                      Source<NavigationController>(controller),
                      NotificationService::NoDetails());
    }
  }

  static void OnOKClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);

    handler->SetAuth(
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->username_entry_))),
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->password_entry_))));
  }

  static void OnCancelClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);
    handler->CancelAuth();
  }

  // True if we've handled auth (SetAuth or CancelAuth has been called).
  bool handled_auth_;
  Lock handled_auth_lock_;

  // The ConstrainedWindow that is hosting our LoginView.
  // This should only be accessed on the ui_loop_.
  ConstrainedWindow* dialog_;

  // The MessageLoop of the thread that the ChromeViewContents lives in.
  MessageLoop* ui_loop_;

  // The request that wants login data.
  // This should only be accessed on the request_loop_.
  URLRequest* request_;

  // The MessageLoop of the thread that the URLRequest lives in.
  MessageLoop* request_loop_;

  // The PasswordForm sent to the PasswordManager. This is so we can refer to it
  // when later notifying the password manager if the credentials were accepted
  // or rejected.
  // This should only be accessed on the ui_loop_.
  PasswordForm password_form_;

  // Points to the password manager owned by the TabContents requesting auth.
  // Can be null if the TabContents is not a TabContents.
  // This should only be accessed on the ui_loop_.
  PasswordManager* password_manager_;

  // Cached from the URLRequest, in case it goes NULL on us.
  int render_process_host_id_;
  int tab_contents_id_;

  // The GtkWidgets that form our visual hierarchy:
  // The root container we pass to our parent.
  OwnedWidgetGtk root_;

  // GtkEntry widgets that the user types into.
  GtkWidget* username_entry_;
  GtkWidget* password_entry_;

  DISALLOW_COPY_AND_ASSIGN(LoginHandlerGtk);
};

// static
LoginHandler* LoginHandler::Create(URLRequest* request, MessageLoop* ui_loop) {
  return new LoginHandlerGtk(request, ui_loop);
}
<commit_msg>Fix missing include.<commit_after>// Copyright (c) 2009 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/login_prompt.h"

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "net/url_request/url_request.h"

using webkit_glue::PasswordForm;

// ----------------------------------------------------------------------------
// LoginHandlerGtk

// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerGtk : public LoginHandler,
                        public base::RefCountedThreadSafe<LoginHandlerGtk>,
                        public ConstrainedWindowGtkDelegate {
 public:
  LoginHandlerGtk(URLRequest* request, MessageLoop* ui_loop)
      : handled_auth_(false),
        dialog_(NULL),
        ui_loop_(ui_loop),
        request_(request),
        request_loop_(MessageLoop::current()),
        password_manager_(NULL) {
    DCHECK(request_) << "LoginHandlerGtk constructed with NULL request";

    AddRef();  // matched by ReleaseLater.
    if (!ResourceDispatcherHost::RenderViewForRequest(request_,
                                                      &render_process_host_id_,
                                                      &tab_contents_id_)) {
      NOTREACHED();
    }
  }

  virtual ~LoginHandlerGtk() {
    root_.Destroy();
  }

  // LoginHandler:
  virtual void BuildViewForPasswordManager(PasswordManager* manager,
                                           std::wstring explanation) {
    DCHECK(MessageLoop::current() == ui_loop_);

    root_.Own(gtk_vbox_new(NULL, gtk_util::kContentAreaBorder));
    GtkWidget* label = gtk_label_new(WideToUTF8(explanation).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(root_.get()), label, FALSE, FALSE, 0);

    username_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);

    password_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);
    gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);

    GtkWidget* table = gtk_util::CreateLabeledControlsGroup(
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_USERNAME_FIELD).c_str(),
        username_entry_,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_PASSWORD_FIELD).c_str(),
        password_entry_,
        NULL);
    gtk_box_pack_start(GTK_BOX(root_.get()), table, FALSE, FALSE, 0);

    GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
    gtk_box_pack_start(GTK_BOX(root_.get()), hbox, FALSE, FALSE, 0);

    GtkWidget* ok = gtk_button_new_from_stock(GTK_STOCK_OK);
    gtk_button_set_label(
        GTK_BUTTON(ok),
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL).c_str());
    g_signal_connect(ok, "clicked", G_CALLBACK(OnOKClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), ok, FALSE, FALSE, 0);

    GtkWidget* cancel = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
    g_signal_connect(cancel, "clicked", G_CALLBACK(OnCancelClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), cancel, FALSE, FALSE, 0);

    // Scary thread safety note: This can potentially be called *after* SetAuth
    // or CancelAuth (say, if the request was cancelled before the UI thread got
    // control).  However, that's OK since any UI interaction in those functions
    // will occur via an InvokeLater on the UI thread, which is guaranteed
    // to happen after this is called (since this was InvokeLater'd first).
    dialog_ = GetTabContentsForLogin()->CreateConstrainedDialog(this);

    // Now that we have attached ourself to the window, we can make our OK
    // button the default action and mess with the focus.
    GTK_WIDGET_SET_FLAGS(ok, GTK_CAN_DEFAULT);
    gtk_widget_grab_default(ok);
    gtk_widget_grab_focus(username_entry_);

    SendNotifications();
  }

  virtual void SetPasswordForm(const webkit_glue::PasswordForm& form) {
    password_form_ = form;
  }

  virtual void SetPasswordManager(PasswordManager* password_manager) {
    password_manager_ = password_manager;
  }

  virtual TabContents* GetTabContentsForLogin() {
    DCHECK(MessageLoop::current() == ui_loop_);

    return tab_util::GetTabContentsByID(render_process_host_id_,
                                        tab_contents_id_);
  }

  virtual void SetAuth(const std::wstring& username,
                       const std::wstring& password) {
    if (WasAuthHandled(true))
      return;

    // Tell the password manager the credentials were submitted / accepted.
    if (password_manager_) {
      password_form_.username_value = username;
      password_form_.password_value = password;
      password_manager_->ProvisionallySavePassword(password_form_);
    }

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SetAuthDeferred, username, password));
  }

  virtual void CancelAuth() {
    if (WasAuthHandled(true))
      return;

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CancelAuthDeferred));
  }

  virtual void OnRequestCancelled() {
    DCHECK(MessageLoop::current() == request_loop_) <<
        "Why is OnRequestCancelled called from the UI thread?";

    // Reference is no longer valid.
    request_ = NULL;

    // Give up on auth if the request was cancelled.
    CancelAuth();
  }

  // Overridden from ConstrainedWindowGtkDelegate:
  virtual GtkWidget* GetWidgetRoot() {
    return root_.get();
  }

  virtual void DeleteDelegate() {
    if (!WasAuthHandled(true)) {
      request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &LoginHandlerGtk::CancelAuthDeferred));
      SendNotifications();
    }

    // Delete this object once all InvokeLaters have been called.
    request_loop_->ReleaseSoon(FROM_HERE, this);
  }

 private:
  friend class LoginPrompt;

  // Calls SetAuth from the request_loop.
  void SetAuthDeferred(const std::wstring& username,
                       const std::wstring& password) {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->SetAuth(username, password);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Calls CancelAuth from the request_loop.
  void CancelAuthDeferred() {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->CancelAuth();
      // Verify that CancelAuth does destroy the request via our delegate.
      DCHECK(request_ != NULL);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Closes the view_contents from the UI loop.
  void CloseContentsDeferred() {
    DCHECK(MessageLoop::current() == ui_loop_);

    // The hosting ConstrainedWindow may have been freed.
    if (dialog_)
      dialog_->CloseConstrainedWindow();
  }

  // Returns whether authentication had been handled (SetAuth or CancelAuth).
  // If |set_handled| is true, it will mark authentication as handled.
  bool WasAuthHandled(bool set_handled) {
    AutoLock lock(handled_auth_lock_);
    bool was_handled = handled_auth_;
    if (set_handled)
      handled_auth_ = true;
    return was_handled;
  }

  // Notify observers that authentication is needed or received.  The automation
  // proxy uses this for testing.
  void SendNotifications() {
    DCHECK(MessageLoop::current() == ui_loop_);

    NotificationService* service = NotificationService::current();
    TabContents* requesting_contents = GetTabContentsForLogin();
    if (!requesting_contents)
      return;

    NavigationController* controller = &requesting_contents->controller();

    if (!WasAuthHandled(false)) {
      LoginNotificationDetails details(this);
      service->Notify(NotificationType::AUTH_NEEDED,
                      Source<NavigationController>(controller),
                      Details<LoginNotificationDetails>(&details));
    } else {
      service->Notify(NotificationType::AUTH_SUPPLIED,
                      Source<NavigationController>(controller),
                      NotificationService::NoDetails());
    }
  }

  static void OnOKClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);

    handler->SetAuth(
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->username_entry_))),
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->password_entry_))));
  }

  static void OnCancelClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);
    handler->CancelAuth();
  }

  // True if we've handled auth (SetAuth or CancelAuth has been called).
  bool handled_auth_;
  Lock handled_auth_lock_;

  // The ConstrainedWindow that is hosting our LoginView.
  // This should only be accessed on the ui_loop_.
  ConstrainedWindow* dialog_;

  // The MessageLoop of the thread that the ChromeViewContents lives in.
  MessageLoop* ui_loop_;

  // The request that wants login data.
  // This should only be accessed on the request_loop_.
  URLRequest* request_;

  // The MessageLoop of the thread that the URLRequest lives in.
  MessageLoop* request_loop_;

  // The PasswordForm sent to the PasswordManager. This is so we can refer to it
  // when later notifying the password manager if the credentials were accepted
  // or rejected.
  // This should only be accessed on the ui_loop_.
  PasswordForm password_form_;

  // Points to the password manager owned by the TabContents requesting auth.
  // Can be null if the TabContents is not a TabContents.
  // This should only be accessed on the ui_loop_.
  PasswordManager* password_manager_;

  // Cached from the URLRequest, in case it goes NULL on us.
  int render_process_host_id_;
  int tab_contents_id_;

  // The GtkWidgets that form our visual hierarchy:
  // The root container we pass to our parent.
  OwnedWidgetGtk root_;

  // GtkEntry widgets that the user types into.
  GtkWidget* username_entry_;
  GtkWidget* password_entry_;

  DISALLOW_COPY_AND_ASSIGN(LoginHandlerGtk);
};

// static
LoginHandler* LoginHandler::Create(URLRequest* request, MessageLoop* ui_loop) {
  return new LoginHandlerGtk(request, ui_loop);
}
<|endoftext|>


<commit_before>/*
 *  dateedit.cpp  -  date entry widget
 *  Program:  kalarm
 *  Copyright © 2002-2008 by David Jarvie <djarvie@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <QMouseEvent>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#include "dateedit.moc"

DateEdit::DateEdit(QWidget* parent)
	: KDateEdit(parent)
{
	connect(this, SIGNAL(dateEntered(const QDate&)), SLOT(newDateEntered(const QDate&)));
}

void DateEdit::setMinDate(const QDate& d, const QString& errorDate)
{
	mMinDate = d;
	if (mMinDate.isValid()  &&  date().isValid()  &&  date() < mMinDate)
		setDate(mMinDate);
	mMinDateErrString = errorDate;
}

void DateEdit::setMaxDate(const QDate& d, const QString& errorDate)
{
	mMaxDate = d;
	if (mMaxDate.isValid()  &&  date().isValid()  &&  date() > mMaxDate)
		setDate(mMaxDate);
	mMaxDateErrString = errorDate;
}

void DateEdit::setInvalid()
{
	setDate(QDate());
}

// Check a new date against any minimum or maximum date.
void DateEdit::newDateEntered(const QDate& newDate)
{
	if (newDate.isValid())
	{
		if (mMinDate.isValid()  &&  newDate < mMinDate)
		{
			pastLimitMessage(mMinDate, mMinDateErrString,
					 ki18nc("@info", "Date cannot be earlier than %1"));
		}
		else if (mMaxDate.isValid()  &&  newDate > mMaxDate)
		{
			pastLimitMessage(mMaxDate, mMaxDateErrString,
					 ki18nc("@info", "Date cannot be later than %1"));
		}
	}
}

void DateEdit::pastLimitMessage(const QDate& limit, const QString& error, const KLocalizedString& defaultError)
{
	QString errString = error;
	if (errString.isNull())
	{
		if (limit == QDate::currentDate())
			errString = i18nc("@info/plain", "today");
		else
			errString = KGlobal::locale()->formatDate(limit, KLocale::ShortDate);
		errString = defaultError.subs(errString).toString();
	}
	KMessageBox::sorry(this, errString);
}

void DateEdit::mousePressEvent(QMouseEvent *e)
{
	if (isReadOnly())
	{
		// Swallow up the event if it's the left button
		if (e->button() == Qt::LeftButton)
			return;
	}
	KDateEdit::mousePressEvent(e);
}

void DateEdit::mouseReleaseEvent(QMouseEvent* e)
{
	if (!isReadOnly())
		KDateEdit::mouseReleaseEvent(e);
}

void DateEdit::mouseMoveEvent(QMouseEvent* e)
{
	if (!isReadOnly())
		KDateEdit::mouseMoveEvent(e);
}

void DateEdit::keyPressEvent(QKeyEvent* e)
{
	if (!isReadOnly())
		KDateEdit::keyPressEvent(e);
}

void DateEdit::keyReleaseEvent(QKeyEvent* e)
{
	if (!isReadOnly())
		KDateEdit::keyReleaseEvent(e);
}
<commit_msg>Prevent date being set outside the allowed range<commit_after>/*
 *  dateedit.cpp  -  date entry widget
 *  Program:  kalarm
 *  Copyright © 2002-2008 by David Jarvie <djarvie@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <QMouseEvent>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#include "dateedit.moc"

DateEdit::DateEdit(QWidget* parent)
	: KDateEdit(parent)
{
	connect(this, SIGNAL(dateEntered(const QDate&)), SLOT(newDateEntered(const QDate&)));
}

void DateEdit::setMinDate(const QDate& d, const QString& errorDate)
{
	mMinDate = d;
	if (mMinDate.isValid()  &&  date().isValid()  &&  date() < mMinDate)
		setDate(mMinDate);
	mMinDateErrString = errorDate;
}

void DateEdit::setMaxDate(const QDate& d, const QString& errorDate)
{
	mMaxDate = d;
	if (mMaxDate.isValid()  &&  date().isValid()  &&  date() > mMaxDate)
		setDate(mMaxDate);
	mMaxDateErrString = errorDate;
}

void DateEdit::setInvalid()
{
	setDate(QDate());
}

// Check a new date against any minimum or maximum date.
void DateEdit::newDateEntered(const QDate& newDate)
{
	if (newDate.isValid())
	{
		if (mMinDate.isValid()  &&  newDate < mMinDate)
		{
			pastLimitMessage(mMinDate, mMinDateErrString,
					 ki18nc("@info", "Date cannot be earlier than %1"));
			setDate(mMinDate);
		}
		else if (mMaxDate.isValid()  &&  newDate > mMaxDate)
		{
			pastLimitMessage(mMaxDate, mMaxDateErrString,
					 ki18nc("@info", "Date cannot be later than %1"));
			setDate(mMaxDate);
		}
	}
}

void DateEdit::pastLimitMessage(const QDate& limit, const QString& error, const KLocalizedString& defaultError)
{
	QString errString = error;
	if (errString.isNull())
	{
		if (limit == QDate::currentDate())
			errString = i18nc("@info/plain", "today");
		else
			errString = KGlobal::locale()->formatDate(limit, KLocale::ShortDate);
		errString = defaultError.subs(errString).toString();
	}
	KMessageBox::sorry(this, errString);
}

void DateEdit::mousePressEvent(QMouseEvent *e)
{
	if (isReadOnly())
	{
		// Swallow up the event if it's the left button
		if (e->button() == Qt::LeftButton)
			return;
	}
	KDateEdit::mousePressEvent(e);
}

void DateEdit::mouseReleaseEvent(QMouseEvent* e)
{
	if (!isReadOnly())
		KDateEdit::mouseReleaseEvent(e);
}

void DateEdit::mouseMoveEvent(QMouseEvent* e)
{
	if (!isReadOnly())
		KDateEdit::mouseMoveEvent(e);
}

void DateEdit::keyPressEvent(QKeyEvent* e)
{
	if (!isReadOnly())
		KDateEdit::keyPressEvent(e);
}

void DateEdit::keyReleaseEvent(QKeyEvent* e)
{
	if (!isReadOnly())
		KDateEdit::keyReleaseEvent(e);
}
<|endoftext|>


<commit_before>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2015  Belledonne Communications SARL.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program 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 Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "configdumper.hh"
#include "module.hh"

using namespace std;

ostream &ConfigDumper::dump(ostream &ostr) const{
	return dump_recursive(ostr, mRoot, 0);
}

ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const
{
	const GenericStruct *cs  = dynamic_cast<const GenericStruct*>(entry);
	const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry);
	if( cs && shouldDumpModule(cs->getName()) ){

		dumpModuleHead(ostr, cs, level);
		for( GenericEntry* child : cs->getChildren() ){
			dump_recursive(ostr, child, level+1);
		}

	} else if( value ){

		dumpModuleValue(ostr, value, level);

	}
	return ostr;
}

#define MODULE_PREFIX_LEN 8 /* strlen("module::") */
bool ConfigDumper::shouldDumpModule(const string& moduleName) const
{
	// When the dumpExperimental is activated, we should dump everything
	if( mDumpExperimental ) return true;

	string name = moduleName;
	if( name.find("module::") != name.npos ){
		name = moduleName.substr(MODULE_PREFIX_LEN);
	}
	auto moduleInfos = ModuleFactory::get()->moduleInfos();
	auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), [name](ModuleInfoBase* i){
			return i->getModuleName() == name;
	});

	ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : nullptr;
	if( moduleInfo != nullptr ){
		return moduleInfo->type() == ModuleTypeProduction;
	} else {
		return true;
	}

}

/* FILE CONFIG DUMPER */

ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const {
	const char *p=help.c_str();
	const char *begin=p;
	const char *origin=help.c_str();

	for(;*p!=0;++p){
		if ((p-begin>60 && *p==' ') || *p=='\n'){
			os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl;
			p++;
			begin=p;
		}
	}
	os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl;
	return os;
}

ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if (val && !val->getExportToConfigFile()) return ostr;
	if( !val->isDeprecated() ){

		printHelp(ostr,val->getHelp(),"#");
		ostr<<"#  Default value: "<<val->getDefault()<<endl;

		if (mDumpDefault) {
			ostr<<val->getName()<<"="<<val->getDefault()<<endl;
		} else {
			ostr<<val->getName()<<"="<<val->get()<<endl;
		}
		ostr << endl;
	}
	return ostr;
}

ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const {
	if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr;

	ostr<<"##"<<endl;

	printHelp(ostr,moduleHead->getHelp(),"##");

	ostr<<"##"<<endl;

	if (level>0){
		ostr<<"["<<moduleHead->getName()<<"]"<<endl;
	}
	else
		ostr<<endl;

	ostr << endl << endl << endl;

	return ostr;
}

/* TexFileComfigDumper */

static void escaper(string &str, char c, const string &replaced) {
	size_t i=0;
	while(string::npos != (i=str.find_first_of(c, i))) {
		str.erase(i, 1);
		str.insert(i, replaced);
		i+=replaced.length();
	}
}

static void string_escaper(string& str, const string &s, const string &replace){
	size_t i=0;
	while(string::npos != (i=str.find(s, i))) {
		str.erase(i, s.length());
		str.insert(i, replace);
		i+=replace.length();
	}
}

string TexFileConfigDumper::escape(const string &strc) const{
	std::string str(strc);
	escaper(str, '_', "\\_");
	escaper(str, '<', "\\textless{}");
	escaper(str, '>', "\\textgreater{}");

	return str;
}

ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const
{
	if (cs->getParent()) {
		string pn=escape(cs->getPrettyName());
		ostr<<"\\section{"<< pn << "}" << endl << endl;
		ostr<<"\\label{" << cs->getName() << "}" << endl;
		ostr<<"\\subsection{Description}"<< endl <<endl;
		ostr<<escape(cs->getHelp())<< endl <<endl;
		ostr<<"\\subsection{Parameters}"<< endl <<endl;
	}
	return ostr;
}

ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {

	if( !val->isDeprecated() ){
		ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl;
		ostr<<escape(val->getHelp())<<endl;
		ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl;
		ostr<<endl;
	}
	return ostr;
}

/* Dokuwiki */

ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if(!val->isDeprecated()){

		// dokuwiki handles line breaks with double backspaces
		string help = val->getHelp();
		escaper(help, '\n', "\\\\ ");
		escaper(help, '`', "'' ");
		string_escaper(help, ". ", ".\\\\ ");

		ostr << "|" << "**" << val->getName() << "**"
		<< " | " << help
		<< " | " << "''" << val->getDefault() << "''"
		<< " | " << val->getTypeName()
		<< " | " << endl;

	}
	return ostr;
}

ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const {
	// we have a generic struc: we're on top level: get module name and description
	ostr << "====" << cs->getPrettyName() << "====" << endl;
	ostr << endl << cs->getHelp() << endl;
	ostr << endl << "Configuration options:" << endl;

	ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl;
	return ostr;
}

/* MIB */

ostream &MibDumper::dump(ostream & ostr)const {
	const time_t t = getCurrentTime();
	char mbstr[100];
	strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t));

	ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl
			<< "IMPORTS" << endl
			<< "	OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl
			<< "	Counter64,NOTIFICATION-TYPE							  	FROM SNMPv2-SMI" << endl
			<< "	MODULE-COMPLIANCE, OBJECT-GROUP       					FROM SNMPv2-CONF;" << endl
			<< endl

			<< "flexisipMIB MODULE-IDENTITY" << endl
			<< "	LAST-UPDATED \"" << mbstr <<"\"" << endl
			<< "	ORGANIZATION \"belledonne-communications\"" << endl
			<< "	CONTACT-INFO \"postal:   34 Avenue de L'europe 38 100 Grenoble France" << endl
			<< "		email:    contact@belledonne-communications.com\"" << endl
			<< "	DESCRIPTION  \"A Flexisip management tree.\"" << endl
			<< "	REVISION     \"" <<mbstr <<"\""<<endl
			<< "    DESCRIPTION  \"" PACKAGE_VERSION << "\"" << endl
			<< "::={ enterprises "<< company_id << " }" << endl
			<< endl;

	dump2(ostr,mRoot,0);
	ostr << "END";
	return ostr;
}

ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{
	GenericStruct *cs=dynamic_cast<GenericStruct*>(entry);
	ConfigValue *cVal;
	StatCounter64 *sVal;
	NotificationEntry *ne;
	string spacing="";
	while (level > 0) {
		spacing += "	";
		--level;
	}
	if (cs && shouldDumpModule(cs->getName())){
		cs->mibFragment(ostr, spacing);
		for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){
			if (!cs->isDeprecated()){
				dump2(ostr,*it,level+1);
				ostr<<endl;
			}
		}
	}else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){
		cVal->mibFragment(ostr, spacing);
	}else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){
		sVal->mibFragment(ostr, spacing);
	}else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){
		ne->mibFragment(ostr,spacing);
	}
	return ostr;
}

<commit_msg>Fix MIB generation (missing end line)<commit_after>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2015  Belledonne Communications SARL.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program 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 Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "configdumper.hh"
#include "module.hh"

using namespace std;

ostream &ConfigDumper::dump(ostream &ostr) const{
	return dump_recursive(ostr, mRoot, 0);
}

ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const
{
	const GenericStruct *cs  = dynamic_cast<const GenericStruct*>(entry);
	const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry);
	if( cs && shouldDumpModule(cs->getName()) ){

		dumpModuleHead(ostr, cs, level);
		for( GenericEntry* child : cs->getChildren() ){
			dump_recursive(ostr, child, level+1);
		}

	} else if( value ){

		dumpModuleValue(ostr, value, level);

	}
	return ostr;
}

#define MODULE_PREFIX_LEN 8 /* strlen("module::") */
bool ConfigDumper::shouldDumpModule(const string& moduleName) const
{
	// When the dumpExperimental is activated, we should dump everything
	if( mDumpExperimental ) return true;

	string name = moduleName;
	if( name.find("module::") != name.npos ){
		name = moduleName.substr(MODULE_PREFIX_LEN);
	}
	auto moduleInfos = ModuleFactory::get()->moduleInfos();
	auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), [name](ModuleInfoBase* i){
			return i->getModuleName() == name;
	});

	ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : nullptr;
	if( moduleInfo != nullptr ){
		return moduleInfo->type() == ModuleTypeProduction;
	} else {
		return true;
	}

}

/* FILE CONFIG DUMPER */

ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const {
	const char *p=help.c_str();
	const char *begin=p;
	const char *origin=help.c_str();

	for(;*p!=0;++p){
		if ((p-begin>60 && *p==' ') || *p=='\n'){
			os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl;
			p++;
			begin=p;
		}
	}
	os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl;
	return os;
}

ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if (val && !val->getExportToConfigFile()) return ostr;
	if( !val->isDeprecated() ){

		printHelp(ostr,val->getHelp(),"#");
		ostr<<"#  Default value: "<<val->getDefault()<<endl;

		if (mDumpDefault) {
			ostr<<val->getName()<<"="<<val->getDefault()<<endl;
		} else {
			ostr<<val->getName()<<"="<<val->get()<<endl;
		}
		ostr << endl;
	}
	return ostr;
}

ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const {
	if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr;

	ostr<<"##"<<endl;

	printHelp(ostr,moduleHead->getHelp(),"##");

	ostr<<"##"<<endl;

	if (level>0){
		ostr<<"["<<moduleHead->getName()<<"]"<<endl;
	}
	else
		ostr<<endl;

	ostr << endl << endl << endl;

	return ostr;
}

/* TexFileComfigDumper */

static void escaper(string &str, char c, const string &replaced) {
	size_t i=0;
	while(string::npos != (i=str.find_first_of(c, i))) {
		str.erase(i, 1);
		str.insert(i, replaced);
		i+=replaced.length();
	}
}

static void string_escaper(string& str, const string &s, const string &replace){
	size_t i=0;
	while(string::npos != (i=str.find(s, i))) {
		str.erase(i, s.length());
		str.insert(i, replace);
		i+=replace.length();
	}
}

string TexFileConfigDumper::escape(const string &strc) const{
	std::string str(strc);
	escaper(str, '_', "\\_");
	escaper(str, '<', "\\textless{}");
	escaper(str, '>', "\\textgreater{}");

	return str;
}

ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const
{
	if (cs->getParent()) {
		string pn=escape(cs->getPrettyName());
		ostr<<"\\section{"<< pn << "}" << endl << endl;
		ostr<<"\\label{" << cs->getName() << "}" << endl;
		ostr<<"\\subsection{Description}"<< endl <<endl;
		ostr<<escape(cs->getHelp())<< endl <<endl;
		ostr<<"\\subsection{Parameters}"<< endl <<endl;
	}
	return ostr;
}

ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {

	if( !val->isDeprecated() ){
		ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl;
		ostr<<escape(val->getHelp())<<endl;
		ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl;
		ostr<<endl;
	}
	return ostr;
}

/* Dokuwiki */

ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if(!val->isDeprecated()){

		// dokuwiki handles line breaks with double backspaces
		string help = val->getHelp();
		escaper(help, '\n', "\\\\ ");
		escaper(help, '`', "'' ");
		string_escaper(help, ". ", ".\\\\ ");

		ostr << "|" << "**" << val->getName() << "**"
		<< " | " << help
		<< " | " << "''" << val->getDefault() << "''"
		<< " | " << val->getTypeName()
		<< " | " << endl;

	}
	return ostr;
}

ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const {
	// we have a generic struc: we're on top level: get module name and description
	ostr << "====" << cs->getPrettyName() << "====" << endl;
	ostr << endl << cs->getHelp() << endl;
	ostr << endl << "Configuration options:" << endl;

	ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl;
	return ostr;
}

/* MIB */

ostream &MibDumper::dump(ostream & ostr)const {
	const time_t t = getCurrentTime();
	char mbstr[100];
	strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t));

	ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl
			<< "IMPORTS" << endl
			<< "	OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl
			<< "	Counter64,NOTIFICATION-TYPE							  	FROM SNMPv2-SMI" << endl
			<< "	MODULE-COMPLIANCE, OBJECT-GROUP       					FROM SNMPv2-CONF;" << endl
			<< endl

			<< "flexisipMIB MODULE-IDENTITY" << endl
			<< "	LAST-UPDATED \"" << mbstr <<"\"" << endl
			<< "	ORGANIZATION \"belledonne-communications\"" << endl
			<< "	CONTACT-INFO \"postal:   34 Avenue de L'europe 38 100 Grenoble France" << endl
			<< "		email:    contact@belledonne-communications.com\"" << endl
			<< "	DESCRIPTION  \"A Flexisip management tree.\"" << endl
			<< "	REVISION     \"" <<mbstr <<"\""<<endl
			<< "    DESCRIPTION  \"" PACKAGE_VERSION << "\"" << endl
			<< "::={ enterprises "<< company_id << " }" << endl
			<< endl;

	dump2(ostr,mRoot,0);
	ostr << "END" << endl;
	return ostr;
}

ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{
	GenericStruct *cs=dynamic_cast<GenericStruct*>(entry);
	ConfigValue *cVal;
	StatCounter64 *sVal;
	NotificationEntry *ne;
	string spacing="";
	while (level > 0) {
		spacing += "	";
		--level;
	}
	if (cs && shouldDumpModule(cs->getName())){
		cs->mibFragment(ostr, spacing);
		for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){
			if (!cs->isDeprecated()){
				dump2(ostr,*it,level+1);
				ostr<<endl;
			}
		}
	}else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){
		cVal->mibFragment(ostr, spacing);
	}else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){
		sVal->mibFragment(ostr, spacing);
	}else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){
		ne->mibFragment(ostr,spacing);
	}
	return ostr;
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * libVLC backend for the Phonon library                                     *
 *                                                                           *
 * Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>               *
 * Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>                *
 * Copyright (C) 2009 Fathi Boudra <fabo@kde.org>                            *
 * Copyright (C) 2009-2010 vlc-phonon AUTHORS                                *
 *                                                                           *
 * This program is free software; you can redistribute it and/or             *
 * modify it under the terms of the GNU Lesser General Public                *
 * License as published by the Free Software Foundation; either              *
 * version 2.1 of the License, or (at your option) any later version.        *
 *                                                                           *
 * This program 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 package; if not, write to the Free Software       *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "vlcloader.h"

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QLibrary>
#include <QtCore/QSettings>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QCoreApplication>

// Global variables
libvlc_instance_t *vlc_instance = 0;

namespace Phonon
{
namespace VLC
{

bool vlcInit(int debugLevl)
{
    // Global variables
    vlc_instance = 0;

    QString path = vlcPath();
    if (!path.isEmpty()) {
        QString pluginsPath = QString("--plugin-path=") + QDir::toNativeSeparators(QFileInfo(vlcPath()).dir().path());

#if defined(Q_OS_UNIX)
        pluginsPath.append("/vlc");
#elif defined(Q_OS_WIN)
        pluginsPath.append("\\plugins");
#endif
        QByteArray p = QFile::encodeName(path);
        QByteArray pp = QFile::encodeName(pluginsPath);

        QByteArray log;
        QByteArray logFile;
        QByteArray verboseLevl;
        if (debugLevl > 0) {
            verboseLevl = QString("--verbose=").append(QString::number(debugLevl)).toLatin1();
            log = "--extraintf=logger";
            logFile = "--logfile=";
#ifdef Q_WS_WIN
            QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc"));
#else
            QDir logFilePath(QDir::homePath().append("/.vlc"));
#endif //Q_WS_WIN
            logFilePath.mkdir("log");
            logFile.append(QFile::encodeName(QDir::toNativeSeparators(logFilePath.path().append("/log/vlc-log-").append(QString::number(qApp->applicationPid())).append(".txt"))));
        }
        // VLC command line options. See vlc --full-help
        const char *vlcArgs[] = {
            p.constData(),
            pp.constData(),
            log.constData(),
            logFile.constData(),
            verboseLevl.constData(),
            "--reset-plugins-cache",
            "--no-media-library",
#ifndef Q_OS_MAC
            "--no-one-instance",
#endif
            "--no-osd",
            "--no-stats",
            "--no-video-title-show",
            "--album-art=0"
        };

        // Create and initialize a libvlc instance (it should be done only once)
        vlc_instance = libvlc_new(sizeof(vlcArgs) / sizeof(*vlcArgs), vlcArgs);
        if (!vlc_instance) {
            qDebug() << "libvlc exception:" << libvlc_errmsg();
        }

        return true;
    }

    return false;
}

void vlcRelease()
{
    libvlc_release(vlc_instance);
    vlcUnload();
}

#if defined(Q_OS_UNIX)
static bool libGreaterThan(const QString &lhs, const QString &rhs)
{
    const QStringList lhsparts = lhs.split(QLatin1Char('.'));
    const QStringList rhsparts = rhs.split(QLatin1Char('.'));
    Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);

    for (int i = 1; i < rhsparts.count(); ++i) {
        if (lhsparts.count() <= i)
            // left hand side is shorter, so it's less than rhs
        {
            return false;
        }

        bool ok = false;
        int b = 0;
        int a = lhsparts.at(i).toInt(&ok);
        if (ok) {
            b = rhsparts.at(i).toInt(&ok);
        }
        if (ok) {
            // both toInt succeeded
            if (a == b) {
                continue;
            }
            return a > b;
        } else {
            // compare as strings;
            if (lhsparts.at(i) == rhsparts.at(i)) {
                continue;
            }
            return lhsparts.at(i) > rhsparts.at(i);
        }
    }

    // they compared strictly equally so far
    // lhs cannot be less than rhs
    return true;
}
#endif

static QStringList findAllLibVlc()
{
    QStringList paths;

#ifdef Q_OS_UNIX
    paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH"))
            .split(QLatin1Char(':'), QString::SkipEmptyParts);
    paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib");

#if defined(Q_WS_MAC)
    paths
            << QCoreApplication::applicationDirPath()
            << QCoreApplication::applicationDirPath() + QLatin1String("/../Frameworks")
            << QCoreApplication::applicationDirPath() + QLatin1String("/../PlugIns")
            << QCoreApplication::applicationDirPath() + QLatin1String("/lib")

            ;
#endif

    QStringList foundVlcs;
    foreach(const QString & path, paths) {
        QDir dir = QDir(path);
        QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files);

        qSort(entryList.begin(), entryList.end(), libGreaterThan);
        foreach(const QString & entry, entryList) {
            if (entry.contains(".debug")) {
                continue;
            }
            foundVlcs << path + QLatin1Char('/') + entry;
        }
    }

    return foundVlcs;
#elif defined(Q_OS_WIN)
    // Read VLC version and installation directory from Windows registry
    QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC");
    QString vlcVersion = settings.value("Version").toString();
    QString vlcInstallDir = settings.value("InstallDir").toString();
    if (vlcVersion.startsWith("1.1") && !vlcInstallDir.isEmpty()) {
        paths << vlcInstallDir + QLatin1Char('\\') + "libvlc.dll";
        return paths;
    } else {
        //If nothing is found in the registry try %PATH%
        QStringList searchPaths = QString::fromLatin1(qgetenv("PATH"))
                                  .split(QLatin1Char(';'), QString::SkipEmptyParts);
        //search also in the application dir
        searchPaths.append(QCoreApplication::applicationDirPath());

        QStringList foundVlcs;
        foreach(const QString & sp, searchPaths) {
            QDir dir = QDir(sp);
            QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files);
            foreach(const QString & entry, entryList){
                foundVlcs << sp + QLatin1Char('\\') + entry;
            }
        }
        paths << foundVlcs;
        return paths;
    }
#endif
}

static QLibrary *vlcLibrary = 0;

QString vlcPath()
{
    static QString path;
    if (!path.isEmpty()) {
        return path;
    }

    vlcLibrary = new QLibrary();
    QStringList paths = findAllLibVlc();
    foreach(path, paths) {
        vlcLibrary->setFileName(path);

        if (!vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+
            return path;
        } else {
            qDebug("Cannot resolve the symbol or load VLC library");
        }
        qWarning() << vlcLibrary->errorString();
    }

    vlcUnload();

    return QString();
}

void vlcUnload()
{
    vlcLibrary->unload();
    delete vlcLibrary;
    vlcLibrary = 0;
}

}
} // Namespace Phonon::VLC
<commit_msg>Disable usage of Xlib<commit_after>/*****************************************************************************
 * libVLC backend for the Phonon library                                     *
 *                                                                           *
 * Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>               *
 * Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>                *
 * Copyright (C) 2009 Fathi Boudra <fabo@kde.org>                            *
 * Copyright (C) 2009-2010 vlc-phonon AUTHORS                                *
 *                                                                           *
 * This program is free software; you can redistribute it and/or             *
 * modify it under the terms of the GNU Lesser General Public                *
 * License as published by the Free Software Foundation; either              *
 * version 2.1 of the License, or (at your option) any later version.        *
 *                                                                           *
 * This program 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 package; if not, write to the Free Software       *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "vlcloader.h"

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QLibrary>
#include <QtCore/QSettings>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QCoreApplication>

// Global variables
libvlc_instance_t *vlc_instance = 0;

namespace Phonon
{
namespace VLC
{

bool vlcInit(int debugLevl)
{
    // Global variables
    vlc_instance = 0;

    QString path = vlcPath();
    if (!path.isEmpty()) {
        QString pluginsPath = QString("--plugin-path=") + QDir::toNativeSeparators(QFileInfo(vlcPath()).dir().path());

#if defined(Q_OS_UNIX)
        pluginsPath.append("/vlc");
#elif defined(Q_OS_WIN)
        pluginsPath.append("\\plugins");
#endif
        QByteArray p = QFile::encodeName(path);
        QByteArray pp = QFile::encodeName(pluginsPath);

        QByteArray log;
        QByteArray logFile;
        QByteArray verboseLevl;
        if (debugLevl > 0) {
            verboseLevl = QString("--verbose=").append(QString::number(debugLevl)).toLatin1();
            log = "--extraintf=logger";
            logFile = "--logfile=";
#ifdef Q_WS_WIN
            QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc"));
#else
            QDir logFilePath(QDir::homePath().append("/.vlc"));
#endif //Q_WS_WIN
            logFilePath.mkdir("log");
            logFile.append(QFile::encodeName(QDir::toNativeSeparators(logFilePath.path().append("/log/vlc-log-").append(QString::number(qApp->applicationPid())).append(".txt"))));
        }
        // VLC command line options. See vlc --full-help
        const char *vlcArgs[] = {
            p.constData(),
            pp.constData(),
            log.constData(),
            logFile.constData(),
            verboseLevl.constData(),
            "--reset-plugins-cache",
            "--no-media-library",
#ifdef Q_WS_X11
            "--no-xlib",
#endif
#ifndef Q_OS_MAC
            "--no-one-instance",
#endif
            "--no-osd",
            "--no-stats",
            "--no-video-title-show",
            "--album-art=0"
        };

        // Create and initialize a libvlc instance (it should be done only once)
        vlc_instance = libvlc_new(sizeof(vlcArgs) / sizeof(*vlcArgs), vlcArgs);
        if (!vlc_instance) {
            qDebug() << "libvlc exception:" << libvlc_errmsg();
        }

        return true;
    }

    return false;
}

void vlcRelease()
{
    libvlc_release(vlc_instance);
    vlcUnload();
}

#if defined(Q_OS_UNIX)
static bool libGreaterThan(const QString &lhs, const QString &rhs)
{
    const QStringList lhsparts = lhs.split(QLatin1Char('.'));
    const QStringList rhsparts = rhs.split(QLatin1Char('.'));
    Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);

    for (int i = 1; i < rhsparts.count(); ++i) {
        if (lhsparts.count() <= i)
            // left hand side is shorter, so it's less than rhs
        {
            return false;
        }

        bool ok = false;
        int b = 0;
        int a = lhsparts.at(i).toInt(&ok);
        if (ok) {
            b = rhsparts.at(i).toInt(&ok);
        }
        if (ok) {
            // both toInt succeeded
            if (a == b) {
                continue;
            }
            return a > b;
        } else {
            // compare as strings;
            if (lhsparts.at(i) == rhsparts.at(i)) {
                continue;
            }
            return lhsparts.at(i) > rhsparts.at(i);
        }
    }

    // they compared strictly equally so far
    // lhs cannot be less than rhs
    return true;
}
#endif

static QStringList findAllLibVlc()
{
    QStringList paths;

#ifdef Q_OS_UNIX
    paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH"))
            .split(QLatin1Char(':'), QString::SkipEmptyParts);
    paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib");

#if defined(Q_WS_MAC)
    paths
            << QCoreApplication::applicationDirPath()
            << QCoreApplication::applicationDirPath() + QLatin1String("/../Frameworks")
            << QCoreApplication::applicationDirPath() + QLatin1String("/../PlugIns")
            << QCoreApplication::applicationDirPath() + QLatin1String("/lib")

            ;
#endif

    QStringList foundVlcs;
    foreach(const QString & path, paths) {
        QDir dir = QDir(path);
        QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files);

        qSort(entryList.begin(), entryList.end(), libGreaterThan);
        foreach(const QString & entry, entryList) {
            if (entry.contains(".debug")) {
                continue;
            }
            foundVlcs << path + QLatin1Char('/') + entry;
        }
    }

    return foundVlcs;
#elif defined(Q_OS_WIN)
    // Read VLC version and installation directory from Windows registry
    QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC");
    QString vlcVersion = settings.value("Version").toString();
    QString vlcInstallDir = settings.value("InstallDir").toString();
    if (vlcVersion.startsWith("1.1") && !vlcInstallDir.isEmpty()) {
        paths << vlcInstallDir + QLatin1Char('\\') + "libvlc.dll";
        return paths;
    } else {
        //If nothing is found in the registry try %PATH%
        QStringList searchPaths = QString::fromLatin1(qgetenv("PATH"))
                                  .split(QLatin1Char(';'), QString::SkipEmptyParts);
        //search also in the application dir
        searchPaths.append(QCoreApplication::applicationDirPath());

        QStringList foundVlcs;
        foreach(const QString & sp, searchPaths) {
            QDir dir = QDir(sp);
            QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files);
            foreach(const QString & entry, entryList){
                foundVlcs << sp + QLatin1Char('\\') + entry;
            }
        }
        paths << foundVlcs;
        return paths;
    }
#endif
}

static QLibrary *vlcLibrary = 0;

QString vlcPath()
{
    static QString path;
    if (!path.isEmpty()) {
        return path;
    }

    vlcLibrary = new QLibrary();
    QStringList paths = findAllLibVlc();
    foreach(path, paths) {
        vlcLibrary->setFileName(path);

        if (!vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+
            return path;
        } else {
            qDebug("Cannot resolve the symbol or load VLC library");
        }
        qWarning() << vlcLibrary->errorString();
    }

    vlcUnload();

    return QString();
}

void vlcUnload()
{
    vlcLibrary->unload();
    delete vlcLibrary;
    vlcLibrary = 0;
}

}
} // Namespace Phonon::VLC
<|endoftext|>


<commit_before>#include "vm/vm.hpp"

#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"

namespace rubinius {
  thread::ThreadData<ManagedThread*> _current_thread;

  ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
    : shared_(ss)
    , kind_(kind)
    , name_(kind == eRuby ? "<ruby>" : "<system>")
    , id_(id)
  {}

  ManagedThread* ManagedThread::current() {
    return _current_thread.get();
  }

  void ManagedThread::set_current(ManagedThread* th) {
    th->os_thread_ = pthread_self();
    _current_thread.set(th);
  }
}
<commit_msg>Add missing initialization of ManagedThread::run_state_<commit_after>#include "vm/vm.hpp"

#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"

namespace rubinius {
  thread::ThreadData<ManagedThread*> _current_thread;

  ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
    : shared_(ss)
    , kind_(kind)
    , name_(kind == eRuby ? "<ruby>" : "<system>")
    , run_state_(eIndependent)
    , id_(id)
  {}

  ManagedThread* ManagedThread::current() {
    return _current_thread.get();
  }

  void ManagedThread::set_current(ManagedThread* th) {
    th->os_thread_ = pthread_self();
    _current_thread.set(th);
  }
}
<|endoftext|>


<commit_before>// Copyright 2013 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 "ozone/wayland/inputs/input_method_event_filter.h"

#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"

namespace ozonewayland {

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:

WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
    : input_method_(ui::CreateInputMethod(this, NULL)) {
  // TODO(yusukes): Check if the root window is currently focused and pass the
  // result to Init().
  input_method_->Init(true);
}

WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:

bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
    const base::NativeEvent& event)
{
}

bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
    ui::EventType type,
    ui::KeyboardCode key_code,
    int flags)
{
}

}  // namespace ozonewayland
<commit_msg>Work around a build error in a very hackish way.<commit_after>// Copyright 2013 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 "ozone/wayland/inputs/input_method_event_filter.h"

#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"

namespace ozonewayland {

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:

WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
    : input_method_(ui::CreateInputMethod(this, 0)) {
  // TODO(yusukes): Check if the root window is currently focused and pass the
  // result to Init().
  input_method_->Init(true);
}

WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:

bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
    const base::NativeEvent& event)
{
}

bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
    ui::EventType type,
    ui::KeyboardCode key_code,
    int flags)
{
}

}  // namespace ozonewayland
<|endoftext|>


<commit_before>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_COMPRESSION)
  #include <botan/compression.h>
#endif

namespace Botan_Tests {

namespace {

const char* text_str =
   "'Twas brillig, and the slithy toves"
   "Did gyre and gimble in the wabe:"
   "All mimsy were the borogoves,"
   "And the mome raths outgrabe."

   "'Beware the Jabberwock, my son!"
   "The jaws that bite, the claws that catch!"
   "Beware the Jubjub bird, and shun"
   "The frumious Bandersnatch!'"

   "He took his vorpal sword in hand;"
   "Long time the manxome foe he sought-"
   "So rested he by the Tumtum tree"
   "And stood awhile in thought."

   "And, as in uffish thought he stood,"
   "The Jabberwock, with eyes of flame,"
   "Came whiffling through the tulgey wood,"
   "And burbled as it came!"

   "One, two! One, two! And through and through"
   "The vorpal blade went snicker-snack!"
   "He left it dead, and with its head"
   "He went galumphing back."

   "'And hast thou slain the Jabberwock?"
   "Come to my arms, my beamish boy!"
   "O frabjous day! Callooh! Callay!'"
   "He chortled in his joy."

   "'Twas brillig, and the slithy toves"
   "Did gyre and gimble in the wabe:"
   "All mimsy were the borogoves,"
   "And the mome raths outgrabe.";

#if defined(BOTAN_HAS_COMPRESSION)

class Compression_Tests : public Test
   {
   public:
      std::vector<Test::Result> run() override
         {
         std::vector<Test::Result> results;
         const size_t text_len = strlen(text_str);

         for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
            {
            try
               {
               Test::Result result(algo + " compression");

               std::unique_ptr<Botan::Compression_Algorithm> c(Botan::make_compressor(algo));
               std::unique_ptr<Botan::Decompression_Algorithm> d(Botan::make_decompressor(algo));

               if(!c || !d)
                  {
                  result.note_missing(algo);
                  continue;
                  }

               result.test_ne("Not the same name", c->name(), d->name());

               const Botan::secure_vector<uint8_t> empty;
               const Botan::secure_vector<uint8_t> all_zeros(text_len, 0);
               const Botan::secure_vector<uint8_t> random_binary = Test::rng().random_vec(text_len);

               const uint8_t* textb = reinterpret_cast<const uint8_t*>(text_str);
               const Botan::secure_vector<uint8_t> text(textb, textb + text_len);

               const size_t c1_e = run_compression(result, 1, *c, *d, empty);
               const size_t c9_e = run_compression(result, 9, *c, *d, empty);
               const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);
               const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);
               const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);
               const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);
               const size_t c1_t = run_compression(result, 1, *c, *d, text);
               const size_t c9_t = run_compression(result, 9, *c, *d, text);

               result.test_gte("Empty input L1 compresses to non-empty output", c1_e, 1);
               result.test_gte("Empty input L9 compresses to non-empty output", c9_e, 1);

               result.test_gte("Level 9 compresses empty at least as well as level 1", c1_e, c9_e);
               result.test_gte("Level 9 compresses zeros at least as well as level 1", c1_z, c9_z);
               result.test_gte("Level 9 compresses random at least as well as level 1", c1_r, c9_r);
               result.test_gte("Level 9 compresses text at least as well as level 1", c1_t, c9_t);

               result.test_lt("Zeros compresses much better than text", c1_z / 8, c1_t);
               result.test_lt("Text compresses much better than random", c1_t / 2, c1_r);

               results.push_back(result);
               }
            catch(std::exception& e)
               {
               results.push_back(Test::Result::Failure("testing " + algo, e.what()));
               }
            }

         return results;
         }

   private:

      // Returns # of bytes of compressed message
      size_t run_compression(Test::Result& result,
                             size_t level,
                             Botan::Compression_Algorithm& c,
                             Botan::Decompression_Algorithm& d,
                             const Botan::secure_vector<uint8_t>& msg)
         {
         Botan::secure_vector<uint8_t> compressed = msg;

         c.start(level);
         c.finish(compressed);

         const size_t c_size = compressed.size();

         Botan::secure_vector<uint8_t> decompressed = compressed;
         d.start();
         d.finish(decompressed);

         result.test_eq("compression round tripped", msg, decompressed);
         return c_size;
         }
   };

BOTAN_REGISTER_TEST("compression", Compression_Tests);

#endif

}

}
<commit_msg>Avoid unused variable warning if compression disabled<commit_after>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_COMPRESSION)
  #include <botan/compression.h>
#endif

namespace Botan_Tests {

#if defined(BOTAN_HAS_COMPRESSION)

namespace {

const char* text_str =
   "'Twas brillig, and the slithy toves"
   "Did gyre and gimble in the wabe:"
   "All mimsy were the borogoves,"
   "And the mome raths outgrabe."

   "'Beware the Jabberwock, my son!"
   "The jaws that bite, the claws that catch!"
   "Beware the Jubjub bird, and shun"
   "The frumious Bandersnatch!'"

   "He took his vorpal sword in hand;"
   "Long time the manxome foe he sought-"
   "So rested he by the Tumtum tree"
   "And stood awhile in thought."

   "And, as in uffish thought he stood,"
   "The Jabberwock, with eyes of flame,"
   "Came whiffling through the tulgey wood,"
   "And burbled as it came!"

   "One, two! One, two! And through and through"
   "The vorpal blade went snicker-snack!"
   "He left it dead, and with its head"
   "He went galumphing back."

   "'And hast thou slain the Jabberwock?"
   "Come to my arms, my beamish boy!"
   "O frabjous day! Callooh! Callay!'"
   "He chortled in his joy."

   "'Twas brillig, and the slithy toves"
   "Did gyre and gimble in the wabe:"
   "All mimsy were the borogoves,"
   "And the mome raths outgrabe.";

class Compression_Tests : public Test
   {
   public:
      std::vector<Test::Result> run() override
         {
         std::vector<Test::Result> results;
         const size_t text_len = strlen(text_str);

         for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
            {
            try
               {
               Test::Result result(algo + " compression");

               std::unique_ptr<Botan::Compression_Algorithm> c(Botan::make_compressor(algo));
               std::unique_ptr<Botan::Decompression_Algorithm> d(Botan::make_decompressor(algo));

               if(!c || !d)
                  {
                  result.note_missing(algo);
                  continue;
                  }

               result.test_ne("Not the same name", c->name(), d->name());

               const Botan::secure_vector<uint8_t> empty;
               const Botan::secure_vector<uint8_t> all_zeros(text_len, 0);
               const Botan::secure_vector<uint8_t> random_binary = Test::rng().random_vec(text_len);

               const uint8_t* textb = reinterpret_cast<const uint8_t*>(text_str);
               const Botan::secure_vector<uint8_t> text(textb, textb + text_len);

               const size_t c1_e = run_compression(result, 1, *c, *d, empty);
               const size_t c9_e = run_compression(result, 9, *c, *d, empty);
               const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);
               const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);
               const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);
               const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);
               const size_t c1_t = run_compression(result, 1, *c, *d, text);
               const size_t c9_t = run_compression(result, 9, *c, *d, text);

               result.test_gte("Empty input L1 compresses to non-empty output", c1_e, 1);
               result.test_gte("Empty input L9 compresses to non-empty output", c9_e, 1);

               result.test_gte("Level 9 compresses empty at least as well as level 1", c1_e, c9_e);
               result.test_gte("Level 9 compresses zeros at least as well as level 1", c1_z, c9_z);
               result.test_gte("Level 9 compresses random at least as well as level 1", c1_r, c9_r);
               result.test_gte("Level 9 compresses text at least as well as level 1", c1_t, c9_t);

               result.test_lt("Zeros compresses much better than text", c1_z / 8, c1_t);
               result.test_lt("Text compresses much better than random", c1_t / 2, c1_r);

               results.push_back(result);
               }
            catch(std::exception& e)
               {
               results.push_back(Test::Result::Failure("testing " + algo, e.what()));
               }
            }

         return results;
         }

   private:

      // Returns # of bytes of compressed message
      size_t run_compression(Test::Result& result,
                             size_t level,
                             Botan::Compression_Algorithm& c,
                             Botan::Decompression_Algorithm& d,
                             const Botan::secure_vector<uint8_t>& msg)
         {
         Botan::secure_vector<uint8_t> compressed = msg;

         c.start(level);
         c.finish(compressed);

         const size_t c_size = compressed.size();

         Botan::secure_vector<uint8_t> decompressed = compressed;
         d.start();
         d.finish(decompressed);

         result.test_eq("compression round tripped", msg, decompressed);
         return c_size;
         }
   };

BOTAN_REGISTER_TEST("compression", Compression_Tests);

#endif

}

}
<|endoftext|>