app_Main.py 472 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from Common import LoudDict
  39. from Common import color_variant
  40. from Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/07/05"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal(str)
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. self.defaults["root_folder_path"] = self.app_home
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### SYS TRAY ##################################################
  598. # ###########################################################################################################
  599. if self.defaults["global_systray_icon"]:
  600. self.parent_w = QtWidgets.QWidget()
  601. if self.cmd_line_headless == 1:
  602. self.trayIcon = FlatCAMSystemTray(app=self,
  603. icon=QtGui.QIcon(self.resource_location +
  604. '/flatcam_icon32_green.png'),
  605. headless=True,
  606. parent=self.parent_w)
  607. else:
  608. self.trayIcon = FlatCAMSystemTray(app=self,
  609. icon=QtGui.QIcon(self.resource_location +
  610. '/flatcam_icon32_green.png'),
  611. parent=self.parent_w)
  612. # ###########################################################################################################
  613. # ############################################### Worker SETUP ##############################################
  614. # ###########################################################################################################
  615. if self.defaults["global_worker_number"]:
  616. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  617. else:
  618. self.workers = WorkerStack(workers_number=2)
  619. self.worker_task.connect(self.workers.add_task)
  620. self.log.debug("Finished creating Workers crew.")
  621. # ###########################################################################################################
  622. # ############################################# Activity Monitor ###########################################
  623. # ###########################################################################################################
  624. # self.activity_view = FlatCAMActivityView(app=self)
  625. # self.ui.infobar.addWidget(self.activity_view)
  626. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  627. # ###########################################################################################################
  628. # ############################################# Signal handling #############################################
  629. # ###########################################################################################################
  630. # ########################################## Custom signals ################################################
  631. # signal for displaying messages in status bar
  632. self.inform[str].connect(self.info)
  633. self.inform[str, bool].connect(self.info)
  634. # signal for displaying messages in the shell
  635. self.inform_shell.connect(self.info_shell)
  636. # signal to be called when the app is quiting
  637. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  638. self.message.connect(lambda: message_dialog(parent=self.ui))
  639. # self.progress.connect(self.set_progress_bar)
  640. # signals emitted when file state change
  641. self.file_opened.connect(self.register_recent)
  642. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  643. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  644. # ########################################## Standard signals ###############################################
  645. # ### Menu
  646. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  647. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  648. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  649. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  650. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  651. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  652. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  653. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  654. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  655. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  656. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  657. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  658. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  659. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  660. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  661. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  662. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  663. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  664. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  665. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  666. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  667. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  668. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  669. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  670. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  671. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  672. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  673. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  674. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  675. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  676. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  677. self.ui.menufile_exit.triggered.connect(self.final_save)
  678. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  679. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  680. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  681. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  682. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  683. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  684. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  685. self.ui.menueditdelete.triggered.connect(self.on_delete)
  686. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  687. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  688. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  689. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  690. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  691. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  692. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  693. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  694. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  695. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  696. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  697. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  698. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  699. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  700. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  701. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  702. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  703. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  704. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  705. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  706. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  707. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  708. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  709. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  710. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  711. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  712. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  713. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  714. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  715. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  716. self.ui.menuview_replot.triggered.connect(self.plot_all)
  717. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  718. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  719. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  720. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  722. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  723. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  724. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  725. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  726. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  727. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  728. self.ui.menuhelp_about.triggered.connect(self.on_about)
  729. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  730. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  731. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  732. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  733. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  734. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  735. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  736. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  737. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  738. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  739. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  740. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  741. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  742. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  743. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  744. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  745. # ToolBar signals
  746. self.connect_toolbar_signals(ui=self.ui)
  747. # Context Menu
  748. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  749. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  750. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  751. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  752. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  753. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  754. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  755. self.ui.clearplot.triggered.connect(self.clear_plots)
  756. self.ui.replot.triggered.connect(self.plot_all)
  757. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  758. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  759. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  760. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  761. self.ui.popmenu_move.triggered.connect(self.obj_move)
  762. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  763. # Project Context Menu -> Color Setting
  764. for act in self.ui.menuprojectcolor.actions():
  765. act.triggered.connect(self.on_set_color_action_triggered)
  766. # ###########################################################################################################
  767. # #################################### GUI PREFERENCES SIGNALS ##############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  770. lambda: self.on_toggle_units(no_pref=False))
  771. # ##################################### Workspace Setting Signals ###########################################
  772. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  773. self.on_workspace_modified)
  774. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  775. self.on_workspace_modified
  776. )
  777. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  778. # ###########################################################################################################
  779. # ######################################## GUI SETTINGS SIGNALS #############################################
  780. # ###########################################################################################################
  781. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  782. # ######################################## Tools related signals ############################################
  783. # portability changed signal
  784. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  785. # Object list
  786. self.object_status_changed.connect(self.collection.on_collection_updated)
  787. # when there are arguments at application startup this get launched
  788. self.args_at_startup[list].connect(self.on_startup_args)
  789. # ###########################################################################################################
  790. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  791. # ###########################################################################################################
  792. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  797. lambda: self.restore_extensions(ext_type='gerber'))
  798. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='excellon'))
  800. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gcode'))
  802. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  803. lambda: self.delete_all_extensions(ext_type='gerber'))
  804. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  809. lambda: self.add_extension(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  815. lambda: self.del_extension(ext_type='gerber'))
  816. # connect the 'Apply' buttons from the Preferences/File Associations
  817. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  822. lambda: self.on_register_files(obj_type='gerber'))
  823. # ###########################################################################################################
  824. # ########################################### KEYWORDS SIGNALS ##############################################
  825. # ###########################################################################################################
  826. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  827. lambda: self.restore_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  829. lambda: self.delete_all_extensions(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  831. lambda: self.add_extension(ext_type='keyword'))
  832. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='keyword'))
  834. # ###########################################################################################################
  835. # ########################################### GUI SIGNALS ###################################################
  836. # ###########################################################################################################
  837. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  838. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  839. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  840. # ###########################################################################################################
  841. # ####################################### VARIOUS SIGNALS ###################################################
  842. # ###########################################################################################################
  843. # connect the abort_all_tasks related slots to the related signals
  844. self.proc_container.idle_flag.connect(self.app_is_idle)
  845. # signal emitted when a tab is closed in the Plot Area
  846. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  847. # signal to close the application
  848. self.close_app_signal.connect(self.kill_app)
  849. # ################################# FINISHED CONNECTING SIGNALS #############################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. # ###########################################################################################################
  853. self.log.debug("Finished connecting Signals.")
  854. # ###########################################################################################################
  855. # ########################################## Other setups ###################################################
  856. # ###########################################################################################################
  857. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  858. # depending on from where those tools are called different actions can be done
  859. self.call_source = 'app'
  860. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  861. self.tool_tab_locked = False
  862. # decide if to show or hide the Notebook side of the screen at startup
  863. if self.defaults["global_project_at_startup"] is True:
  864. self.ui.splitter.setSizes([1, 1])
  865. else:
  866. self.ui.splitter.setSizes([0, 1])
  867. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  868. self.setup_component_editor()
  869. # ###########################################################################################################
  870. # ####################################### Auto-complete KEYWORDS ############################################
  871. # ###########################################################################################################
  872. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  873. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  874. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  875. 'export_exc',
  876. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  877. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  878. 'interiors', 'isolate', 'join_excellon',
  879. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  880. 'mirror', 'ncc',
  881. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  882. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  883. 'options', 'origin',
  884. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  885. 'save', 'save_project',
  886. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  887. 'skew', 'subtract_poly', 'subtract_rectangle',
  888. 'version', 'write_gcode'
  889. ]
  890. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  891. 'Paste_1',
  892. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  893. 'Toolchange_manual', 'True', 'Users',
  894. 'all', 'auto', 'axis',
  895. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  896. 'contour', 'default',
  897. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  898. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  899. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  900. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  901. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  902. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  903. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  904. 'spacing_columns',
  905. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  906. 'toolchange_xy', 'toolchangez', 'travelz',
  907. 'tooldia', 'use_threads', 'value',
  908. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  909. ]
  910. self.tcl_keywords = [
  911. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  912. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  913. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  914. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  915. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  916. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  917. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  918. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  919. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  920. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  921. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  922. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  923. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  924. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  925. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  926. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  927. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  928. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  929. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  930. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  931. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  932. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  933. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  934. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  935. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  936. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  937. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  938. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  939. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  940. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  941. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  942. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  943. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  944. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  945. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  946. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  947. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  948. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  949. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  950. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  951. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  952. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  953. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  954. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  955. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  956. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  957. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  958. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  959. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  960. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  961. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  962. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  963. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  964. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  965. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  966. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  967. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  968. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  969. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  970. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  971. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  972. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  973. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  974. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  975. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  976. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  977. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  978. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  979. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  980. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  981. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  982. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  983. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  984. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  985. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  986. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  987. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  988. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  989. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  990. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  991. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  992. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  993. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  994. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  995. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  996. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  997. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  998. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  999. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1000. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1001. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1002. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1003. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1004. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1005. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1006. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1007. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1008. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1009. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1010. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1011. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1012. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1013. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1014. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1015. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1016. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1017. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1018. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1019. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1020. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1021. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1022. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1023. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1024. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1025. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1026. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1027. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1028. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1029. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1030. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1031. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1032. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1033. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1034. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1035. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1036. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1037. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1038. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1039. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1040. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1041. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1042. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1043. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1044. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1045. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1046. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1047. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1048. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1049. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1050. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1051. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1052. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1053. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1054. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1055. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1056. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1057. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1058. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1059. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1060. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1061. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1062. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1063. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1064. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1065. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1066. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1067. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1068. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1069. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1070. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1071. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1072. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1073. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1074. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1075. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1076. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1077. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1078. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1079. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1080. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1081. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1082. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1083. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1084. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1085. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1086. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1087. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1088. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1089. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1090. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1091. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1092. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1093. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1094. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1095. ]
  1096. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1097. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  1101. self.shell = None
  1102. self.dblsidedtool = None
  1103. self.distance_tool = None
  1104. self.distance_min_tool = None
  1105. self.panelize_tool = None
  1106. self.film_tool = None
  1107. self.paste_tool = None
  1108. self.calculator_tool = None
  1109. self.rules_tool = None
  1110. self.sub_tool = None
  1111. self.move_tool = None
  1112. self.cutout_tool = None
  1113. self.ncclear_tool = None
  1114. self.paint_tool = None
  1115. self.isolation_tool = None
  1116. self.drilling_tool = None
  1117. self.optimal_tool = None
  1118. self.transform_tool = None
  1119. self.properties_tool = None
  1120. self.pdf_tool = None
  1121. self.image_tool = None
  1122. self.pcb_wizard_tool = None
  1123. self.cal_exc_tool = None
  1124. self.qrcode_tool = None
  1125. self.copper_thieving_tool = None
  1126. self.fiducial_tool = None
  1127. self.edrills_tool = None
  1128. self.align_objects_tool = None
  1129. self.punch_tool = None
  1130. self.invert_tool = None
  1131. self.corners_tool = None
  1132. self.etch_tool = None
  1133. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1134. try:
  1135. self.install_tools()
  1136. except AttributeError as e:
  1137. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1138. # ###########################################################################################################
  1139. # ############################################ SETUP RECENT ITEMS ###########################################
  1140. # ###########################################################################################################
  1141. self.setup_recent_items()
  1142. # ###########################################################################################################
  1143. # ######################################### BookMarks Manager ###############################################
  1144. # ###########################################################################################################
  1145. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1146. self.install_bookmarks()
  1147. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1148. # ###########################################################################################################
  1149. # ########################################### Tools Database ################################################
  1150. # ###########################################################################################################
  1151. self.tools_db_tab = None
  1152. # ### System Font Parsing ###
  1153. # self.f_parse = ParseFont(self)
  1154. # self.parse_system_fonts()
  1155. # ###########################################################################################################
  1156. # ############################################## Shell SETUP ################################################
  1157. # ###########################################################################################################
  1158. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1159. if self.defaults["global_shell_at_startup"]:
  1160. self.ui.shell_dock.show()
  1161. else:
  1162. self.ui.shell_dock.hide()
  1163. # ###########################################################################################################
  1164. # ######################################### Check for updates ###############################################
  1165. # ###########################################################################################################
  1166. # Separate thread (Not worker)
  1167. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1168. if (self.beta is False or self.beta is None) and \
  1169. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1170. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1171. # self.thr2 = QtCore.QThread()
  1172. self.worker_task.emit({'fcn': self.version_check,
  1173. 'params': []})
  1174. # self.thr2.start(QtCore.QThread.LowPriority)
  1175. # ###########################################################################################################
  1176. # ##################################### Register files with FlatCAM; #######################################
  1177. # ################################### It works only for Windows for now ####################################
  1178. # ###########################################################################################################
  1179. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1180. self.on_register_files()
  1181. # ###########################################################################################################
  1182. # ######################################## Variables for global usage #######################################
  1183. # ###########################################################################################################
  1184. # hold the App units
  1185. self.units = 'MM'
  1186. # coordinates for relative position display
  1187. self.rel_point1 = (0, 0)
  1188. self.rel_point2 = (0, 0)
  1189. # variable to store coordinates
  1190. self.pos = (0, 0)
  1191. self.pos_canvas = (0, 0)
  1192. self.pos_jump = (0, 0)
  1193. # variable to store mouse coordinates
  1194. self.mouse = [0, 0]
  1195. # variable to store the delta positions on cavnas
  1196. self.dx = 0
  1197. self.dy = 0
  1198. # decide if we have a double click or single click
  1199. self.doubleclick = False
  1200. # store here the is_dragging value
  1201. self.event_is_dragging = False
  1202. # variable to store if a command is active (then the var is not None) and which one it is
  1203. self.command_active = None
  1204. # variable to store the status of moving selection action
  1205. # None value means that it's not an selection action
  1206. # True value = a selection from left to right
  1207. # False value = a selection from right to left
  1208. self.selection_type = None
  1209. # List to store the objects that are currently loaded in FlatCAM
  1210. # This list is updated on each object creation or object delete
  1211. self.all_objects_list = []
  1212. self.objects_under_the_click_list = []
  1213. # List to store the objects that are selected
  1214. self.sel_objects_list = []
  1215. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1216. self.key_modifiers = None
  1217. # Variable to store the status of the code editor
  1218. self.toggle_codeeditor = False
  1219. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1220. self.click_noproject = False
  1221. self.cursor = None
  1222. # Variable to store the GCODE that was edited
  1223. self.gcode_edited = ""
  1224. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  1225. self.old_state_of_tools_toolbar = False
  1226. self.text_editor_tab = None
  1227. # reference for the self.ui.code_editor
  1228. self.reference_code_editor = None
  1229. self.script_code = ''
  1230. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1231. self.tools_db_changed_flag = False
  1232. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1233. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1234. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1235. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1236. 'tsm']
  1237. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1238. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1239. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1240. 'sbp', 'tap', 'xpi']
  1241. self.svg_list = ['svg']
  1242. self.dxf_list = ['dxf']
  1243. self.pdf_list = ['pdf']
  1244. self.prj_list = ['flatprj']
  1245. self.conf_list = ['flatconfig']
  1246. # last used filters
  1247. self.last_op_gerber_filter = None
  1248. self.last_op_excellon_filter = None
  1249. self.last_op_gcode_filter = None
  1250. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1251. # flag for polygons not cleared
  1252. self.poly_not_cleared = False
  1253. # VisPy visuals
  1254. self.isHovering = False
  1255. self.notHovering = True
  1256. # Window geometry
  1257. self.x_pos = None
  1258. self.y_pos = None
  1259. self.width = None
  1260. self.height = None
  1261. # when True, the app has to return from any thread
  1262. self.abort_flag = False
  1263. # set the value used in the Windows Title
  1264. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1265. # this holds a widget that is installed in the Plot Area when View Source option is used
  1266. self.source_editor_tab = None
  1267. self.pagesize = {}
  1268. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1269. # VisPy visuals
  1270. if self.is_legacy is False:
  1271. try:
  1272. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1273. except AttributeError:
  1274. self.tool_shapes = None
  1275. else:
  1276. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1277. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1278. # used in the delayed shutdown self.start_delayed_quit() method
  1279. self.save_timer = None
  1280. # ###########################################################################################################
  1281. # ################################## ADDING FlatCAM EDITORS section #########################################
  1282. # ###########################################################################################################
  1283. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1284. # at the first launch of the App , the editors will not be functional.
  1285. try:
  1286. self.geo_editor = AppGeoEditor(self)
  1287. except Exception as es:
  1288. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1289. try:
  1290. self.exc_editor = AppExcEditor(self)
  1291. except Exception as es:
  1292. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1293. try:
  1294. self.grb_editor = AppGerberEditor(self)
  1295. except Exception as es:
  1296. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1297. try:
  1298. self.gcode_editor = AppGCodeEditor(self)
  1299. except Exception as es:
  1300. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1301. self.log.debug("Finished adding FlatCAM Editor's.")
  1302. self.set_ui_title(name=_("New Project - Not saved"))
  1303. current_platform = platform.architecture()[0]
  1304. if current_platform != '64bit':
  1305. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1306. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1307. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1308. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1309. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1310. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1311. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1312. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1313. # ###########################################################################################################
  1314. # ########################################### EXCLUSION AREAS ###############################################
  1315. # ###########################################################################################################
  1316. self.exc_areas = ExclusionAreas(app=self)
  1317. # ###########################################################################################################
  1318. # ##################################### Finished the CONSTRUCTOR ############################################
  1319. # ###########################################################################################################
  1320. App.log.debug("END of constructor. Releasing control.")
  1321. # ###########################################################################################################
  1322. # ########################################## SHOW GUI #######################################################
  1323. # ###########################################################################################################
  1324. # if the app is not started as headless, show it
  1325. if self.cmd_line_headless != 1:
  1326. if show_splash:
  1327. # finish the splash
  1328. self.splash.finish(self.ui)
  1329. mgui_settings = QSettings("Open Source", "FlatCAM")
  1330. if mgui_settings.contains("maximized_gui"):
  1331. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1332. if maximized_ui is True:
  1333. self.ui.showMaximized()
  1334. else:
  1335. self.ui.show()
  1336. else:
  1337. self.ui.show()
  1338. if self.defaults["global_systray_icon"]:
  1339. self.trayIcon.show()
  1340. else:
  1341. log.warning("******************* RUNNING HEADLESS *******************")
  1342. # ###########################################################################################################
  1343. # ######################################## START-UP ARGUMENTS ###############################################
  1344. # ###########################################################################################################
  1345. # test if the program was started with a script as parameter
  1346. if self.cmd_line_shellvar:
  1347. try:
  1348. cnt = 0
  1349. command_tcl = 0
  1350. for i in self.cmd_line_shellvar.split(','):
  1351. if i is not None:
  1352. # noinspection PyBroadException
  1353. try:
  1354. command_tcl = eval(i)
  1355. except Exception:
  1356. command_tcl = i
  1357. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1358. cnt += 1
  1359. # if there are Windows paths then replace the path separator with a Unix like one
  1360. if sys.platform == 'win32':
  1361. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1362. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1363. except Exception as ext:
  1364. print("ERROR: ", ext)
  1365. sys.exit(2)
  1366. if self.cmd_line_shellfile:
  1367. if self.cmd_line_headless != 1:
  1368. if self.ui.shell_dock.isHidden():
  1369. self.ui.shell_dock.show()
  1370. try:
  1371. with open(self.cmd_line_shellfile, "r") as myfile:
  1372. # if show_splash:
  1373. # self.splash.showMessage('%s: %ssec\n%s' % (
  1374. # _("Canvas initialization started.\n"
  1375. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1376. # _("Executing Tcl Script ...")),
  1377. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1378. # color=QtGui.QColor("gray"))
  1379. cmd_line_shellfile_text = myfile.read()
  1380. if self.cmd_line_headless != 1:
  1381. self.shell.exec_command(cmd_line_shellfile_text)
  1382. else:
  1383. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1384. except Exception as ext:
  1385. print("ERROR: ", ext)
  1386. sys.exit(2)
  1387. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1388. # the path/file_name must be enclosed in quotes if it contain spaces
  1389. if App.args:
  1390. self.args_at_startup.emit(App.args)
  1391. if self.defaults.old_defaults_found is True:
  1392. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1393. "Please reboot the application to update."))
  1394. self.defaults.old_defaults_found = False
  1395. # ######################################### INIT FINISHED #######################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. @staticmethod
  1402. def copy_and_overwrite(from_path, to_path):
  1403. """
  1404. From here:
  1405. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1406. :param from_path: source path
  1407. :param to_path: destination path
  1408. :return: None
  1409. """
  1410. if os.path.exists(to_path):
  1411. shutil.rmtree(to_path)
  1412. try:
  1413. shutil.copytree(from_path, to_path)
  1414. except FileNotFoundError:
  1415. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1416. shutil.copytree(from_new_path, to_path)
  1417. def on_startup_args(self, args, silent=False):
  1418. """
  1419. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1420. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1421. :param args: a list containing the application args at startup
  1422. :return: None
  1423. """
  1424. if args is not None:
  1425. args_to_process = args
  1426. else:
  1427. args_to_process = App.args
  1428. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1429. for argument in args_to_process:
  1430. if '.FlatPrj'.lower() in argument.lower():
  1431. try:
  1432. project_name = str(argument)
  1433. if project_name == "":
  1434. if silent is False:
  1435. self.inform.emit(_("Cancelled."))
  1436. else:
  1437. # self.open_project(project_name)
  1438. run_from_arg = True
  1439. # self.worker_task.emit({'fcn': self.open_project,
  1440. # 'params': [project_name, run_from_arg]})
  1441. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1442. except Exception as e:
  1443. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1444. elif '.FlatConfig'.lower() in argument.lower():
  1445. try:
  1446. file_name = str(argument)
  1447. if file_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Open Config file failed."))
  1450. else:
  1451. run_from_arg = True
  1452. # self.worker_task.emit({'fcn': self.open_config_file,
  1453. # 'params': [file_name, run_from_arg]})
  1454. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1455. except Exception as e:
  1456. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1457. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1458. try:
  1459. file_name = str(argument)
  1460. if file_name == "":
  1461. if silent is False:
  1462. self.inform.emit(_("Open Script file failed."))
  1463. else:
  1464. if silent is False:
  1465. self.on_fileopenscript(name=file_name)
  1466. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1467. self.on_filerunscript(name=file_name)
  1468. except Exception as e:
  1469. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1470. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1471. log.debug("App.on_startup_args() --> Quit event.")
  1472. sys.exit()
  1473. elif 'save'.lower() in argument.lower():
  1474. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1475. self.preferencesUiManager.save_defaults()
  1476. else:
  1477. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1478. proc_arg = argument.lower()
  1479. for ext in exc_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open Excellon file failed."))
  1487. else:
  1488. self.on_fileopenexcellon(name=file_name, signal=None)
  1489. return
  1490. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1491. for ext in gco_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open GCode file failed."))
  1499. else:
  1500. self.on_fileopengcode(name=file_name, signal=None)
  1501. return
  1502. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1503. for ext in grb_list:
  1504. proc_ext = ext.replace(' ', '')
  1505. proc_ext = '.%s' % proc_ext
  1506. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1507. file_name = str(argument)
  1508. if file_name == "":
  1509. if silent is False:
  1510. self.inform.emit(_("Open Gerber file failed."))
  1511. else:
  1512. self.on_fileopengerber(name=file_name, signal=None)
  1513. return
  1514. # if it reached here without already returning then the app was registered with a file that it does not
  1515. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1516. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1517. # for arg in args_to_process:
  1518. # if 'FlatCAM.exe' in arg:
  1519. # continue
  1520. # else:
  1521. # sys.exit(2)
  1522. def set_ui_title(self, name):
  1523. """
  1524. Sets the title of the main window.
  1525. :param name: String that store the project path and project name
  1526. :return: None
  1527. """
  1528. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1529. (self.version,
  1530. ('BETA' if self.beta else ''),
  1531. platform.architecture()[0],
  1532. self.engine,
  1533. name)
  1534. )
  1535. def on_app_restart(self):
  1536. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1537. # be left in the SySTray
  1538. try:
  1539. self.trayIcon.hide()
  1540. except Exception:
  1541. pass
  1542. fcTranslate.restart_program(app=self)
  1543. def clear_pool(self):
  1544. """
  1545. Clear the multiprocessing pool and calls garbage collector.
  1546. :return: None
  1547. """
  1548. self.pool.close()
  1549. self.pool = Pool()
  1550. self.pool_recreated.emit(self.pool)
  1551. gc.collect()
  1552. def install_tools(self):
  1553. """
  1554. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1555. Instantiation of the Tools classes.
  1556. The order that the tools are installed is important as they can depend on each other install position.
  1557. :return: None
  1558. """
  1559. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1560. self.shell = FCShell(app=self, version=self.version)
  1561. self.distance_tool = Distance(self)
  1562. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1563. before=self.ui.menueditorigin,
  1564. separator=False)
  1565. self.distance_min_tool = DistanceMin(self)
  1566. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1567. pos=self.ui.menuedit,
  1568. before=self.ui.menueditorigin,
  1569. separator=True)
  1570. self.dblsidedtool = DblSidedTool(self)
  1571. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1572. self.cal_exc_tool = ToolCalibration(self)
  1573. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1574. before=self.dblsidedtool.menuAction,
  1575. separator=False)
  1576. self.align_objects_tool = AlignObjects(self)
  1577. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1578. self.edrills_tool = ToolExtractDrills(self)
  1579. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1580. self.panelize_tool = Panelize(self)
  1581. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1582. self.film_tool = Film(self)
  1583. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1584. self.paste_tool = SolderPaste(self)
  1585. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1586. self.calculator_tool = ToolCalculator(self)
  1587. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1588. self.sub_tool = ToolSub(self)
  1589. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1590. pos=self.ui.menutool, separator=True)
  1591. self.rules_tool = RulesCheck(self)
  1592. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1593. pos=self.ui.menutool, separator=False)
  1594. self.optimal_tool = ToolOptimal(self)
  1595. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1596. pos=self.ui.menutool, separator=True)
  1597. self.move_tool = ToolMove(self)
  1598. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1599. before=self.ui.menueditorigin, separator=True)
  1600. self.cutout_tool = CutOut(self)
  1601. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction)
  1603. self.ncclear_tool = NonCopperClear(self)
  1604. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1605. before=self.sub_tool.menuAction, separator=True)
  1606. self.paint_tool = ToolPaint(self)
  1607. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1608. before=self.sub_tool.menuAction, separator=True)
  1609. self.isolation_tool = ToolIsolation(self)
  1610. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1611. before=self.sub_tool.menuAction, separator=True)
  1612. self.drilling_tool = ToolDrilling(self)
  1613. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1614. before=self.sub_tool.menuAction, separator=True)
  1615. self.copper_thieving_tool = ToolCopperThieving(self)
  1616. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1617. pos=self.ui.menutool)
  1618. self.fiducial_tool = ToolFiducials(self)
  1619. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1620. pos=self.ui.menutool)
  1621. self.qrcode_tool = QRCode(self)
  1622. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1623. pos=self.ui.menutool)
  1624. self.punch_tool = ToolPunchGerber(self)
  1625. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1626. self.invert_tool = ToolInvertGerber(self)
  1627. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1628. self.corners_tool = ToolCorners(self)
  1629. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1630. self.etch_tool = ToolEtchCompensation(self)
  1631. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1632. self.transform_tool = ToolTransform(self)
  1633. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1634. pos=self.ui.menuoptions, separator=True)
  1635. self.properties_tool = Properties(self)
  1636. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1637. pos=self.ui.menuoptions)
  1638. self.pdf_tool = ToolPDF(self)
  1639. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1640. pos=self.ui.menufileimport,
  1641. separator=True)
  1642. self.image_tool = ToolImage(self)
  1643. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1644. pos=self.ui.menufileimport,
  1645. separator=True)
  1646. self.pcb_wizard_tool = PcbWizard(self)
  1647. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1648. pos=self.ui.menufileimport)
  1649. self.log.debug("Tools are installed.")
  1650. def remove_tools(self):
  1651. """
  1652. Will remove all the actions in the Tool menu.
  1653. :return: None
  1654. """
  1655. for act in self.ui.menutool.actions():
  1656. self.ui.menutool.removeAction(act)
  1657. def init_tools(self):
  1658. """
  1659. Initialize the Tool tab in the notebook side of the central widget.
  1660. Remove the actions in the Tools menu.
  1661. Instantiate again the FlatCAM tools (plugins).
  1662. All this is required when changing the layout: standard, compact etc.
  1663. :return: None
  1664. """
  1665. log.debug("init_tools()")
  1666. # delete the data currently in the Tools Tab and the Tab itself
  1667. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1668. if widget is not None:
  1669. widget.deleteLater()
  1670. self.ui.notebook.removeTab(2)
  1671. # rebuild the Tools Tab
  1672. self.ui.tool_tab = QtWidgets.QWidget()
  1673. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1674. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1675. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1676. self.ui.tool_scroll_area = VerticalScrollArea()
  1677. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1678. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1679. # first remove all of them
  1680. self.remove_tools()
  1681. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1682. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1683. '&Command Line\tS')
  1684. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1685. # third install all of them
  1686. try:
  1687. self.install_tools()
  1688. except AttributeError:
  1689. pass
  1690. self.log.debug("Tools are initialized.")
  1691. # def parse_system_fonts(self):
  1692. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1693. # 'params': []})
  1694. def connect_tools_signals_to_toolbar(self, ui):
  1695. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1696. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1697. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1698. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1699. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1700. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1701. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1702. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1703. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1704. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1705. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1706. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1707. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1708. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1709. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1710. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1711. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1712. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1713. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1714. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1715. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1716. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1717. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1718. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1719. def connect_toolbar_signals(self, ui):
  1720. """
  1721. Reconnect the signals to the actions in the toolbar.
  1722. This has to be done each time after the FlatCAM tools are removed/installed.
  1723. :return: None
  1724. """
  1725. # Toolbar
  1726. # File Toolbar Signals
  1727. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1728. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1729. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1730. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1731. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1732. # View Toolbar Signals
  1733. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1734. ui.replot_btn.triggered.connect(self.plot_all)
  1735. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1736. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1737. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1738. # Edit Toolbar Signals
  1739. ui.editgeo_btn.triggered.connect(self.object2editor)
  1740. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1741. ui.copy_btn.triggered.connect(self.on_copy_command)
  1742. ui.delete_btn.triggered.connect(self.on_delete)
  1743. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1744. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1745. ui.origin_btn.triggered.connect(self.on_set_origin)
  1746. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1747. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1748. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1749. # Scripting Toolbar Signals
  1750. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1751. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1752. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1753. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1754. # Tools Toolbar Signals
  1755. try:
  1756. self.connect_tools_signals_to_toolbar(ui=ui)
  1757. except Exception as err:
  1758. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1759. def object2editor(self):
  1760. """
  1761. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1762. :return: None
  1763. """
  1764. self.defaults.report_usage("object2editor()")
  1765. # disable the objects menu as it may interfere with the appEditors
  1766. self.ui.menuobjects.setDisabled(True)
  1767. edited_object = self.collection.get_active()
  1768. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1769. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1770. pass
  1771. else:
  1772. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1773. return
  1774. if isinstance(edited_object, GeometryObject):
  1775. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1776. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1777. # we set the notebook to hidden
  1778. # self.ui.splitter.setSizes([0, 1])
  1779. if edited_object.multigeo is True:
  1780. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1781. if len(sel_rows) > 1:
  1782. self.inform.emit('[WARNING_NOTCL] %s' %
  1783. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1784. "is not possible.\n"
  1785. "Edit only one geometry at a time."))
  1786. if not sel_rows:
  1787. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1788. return
  1789. # determine the tool dia of the selected tool
  1790. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1791. # now find the key in the edited_object.tools that has this tooldia
  1792. multi_tool = 1
  1793. for tool in edited_object.tools:
  1794. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1795. multi_tool = tool
  1796. break
  1797. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1798. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1799. else:
  1800. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1801. self.geo_editor.edit_fcgeometry(edited_object)
  1802. # set call source to the Editor we go into
  1803. self.call_source = 'geo_editor'
  1804. elif isinstance(edited_object, ExcellonObject):
  1805. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1806. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1807. if self.ui.splitter.sizes()[0] == 0:
  1808. self.ui.splitter.setSizes([1, 1])
  1809. self.exc_editor.edit_fcexcellon(edited_object)
  1810. # set call source to the Editor we go into
  1811. self.call_source = 'exc_editor'
  1812. elif isinstance(edited_object, GerberObject):
  1813. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1814. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1815. if self.ui.splitter.sizes()[0] == 0:
  1816. self.ui.splitter.setSizes([1, 1])
  1817. self.grb_editor.edit_fcgerber(edited_object)
  1818. # set call source to the Editor we go into
  1819. self.call_source = 'grb_editor'
  1820. # reset the following variables so the UI is built again after edit
  1821. edited_object.ui_build = False
  1822. elif isinstance(edited_object, CNCJobObject):
  1823. if self.ui.splitter.sizes()[0] == 0:
  1824. self.ui.splitter.setSizes([1, 1])
  1825. # set call source to the Editor we go into
  1826. self.call_source = 'gcode_editor'
  1827. self.gcode_editor.edit_fcgcode(edited_object)
  1828. # make sure that we can't select another object while in Editor Mode:
  1829. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1830. self.ui.project_frame.setDisabled(True)
  1831. # delete any selection shape that might be active as they are not relevant in Editor
  1832. self.delete_selection_shape()
  1833. # hide the Tools Toolbar
  1834. tools_tb = self.ui.toolbartools
  1835. if tools_tb.isVisible():
  1836. self.old_state_of_tools_toolbar = True
  1837. tools_tb.hide()
  1838. else:
  1839. self.old_state_of_tools_toolbar = False
  1840. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1841. self.ui.plot_tab_area.protectTab(0)
  1842. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1843. self.should_we_save = True
  1844. def editor2object(self, cleanup=None):
  1845. """
  1846. Transfers the Geometry or Excellon from it's editor to the current object.
  1847. :return: None
  1848. """
  1849. self.defaults.report_usage("editor2object()")
  1850. # re-enable the objects menu that was disabled on entry in Editor mode
  1851. self.ui.menuobjects.setDisabled(False)
  1852. # do not update a geometry or excellon object unless it comes out of an editor
  1853. if self.call_source != 'app':
  1854. edited_obj = self.collection.get_active()
  1855. if cleanup is None:
  1856. msgbox = QtWidgets.QMessageBox()
  1857. msgbox.setText(_("Do you want to save the edited object?"))
  1858. msgbox.setWindowTitle(_("Close Editor"))
  1859. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1860. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1861. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1862. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1863. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1864. msgbox.setDefaultButton(bt_yes)
  1865. msgbox.exec_()
  1866. response = msgbox.clickedButton()
  1867. if response == bt_yes:
  1868. # show the Tools Toolbar
  1869. tools_tb = self.ui.toolbartools
  1870. if self.old_state_of_tools_toolbar is True:
  1871. tools_tb.show()
  1872. # clean the Tools Tab
  1873. self.ui.tool_scroll_area.takeWidget()
  1874. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1875. self.ui.notebook.setTabText(2, "Tool")
  1876. if edited_obj.kind == 'geometry':
  1877. obj_type = "Geometry"
  1878. self.geo_editor.update_fcgeometry(edited_obj)
  1879. # self.geo_editor.update_options(edited_obj)
  1880. # restore GUI to the Selected TAB
  1881. # Remove anything else in the appGUI
  1882. self.ui.tool_scroll_area.takeWidget()
  1883. # update the geo object options so it is including the bounding box values
  1884. try:
  1885. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1886. edited_obj.options['xmin'] = xmin
  1887. edited_obj.options['ymin'] = ymin
  1888. edited_obj.options['xmax'] = xmax
  1889. edited_obj.options['ymax'] = ymax
  1890. except AttributeError as e:
  1891. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1892. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1893. edited_obj.build_ui()
  1894. edited_obj.plot()
  1895. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1896. elif edited_obj.kind == 'gerber':
  1897. obj_type = "Gerber"
  1898. self.grb_editor.update_fcgerber()
  1899. # self.grb_editor.update_options(edited_obj)
  1900. # delete the old object (the source object) if it was an empty one
  1901. try:
  1902. if len(edited_obj.solid_geometry) == 0:
  1903. old_name = edited_obj.options['name']
  1904. self.collection.delete_by_name(old_name)
  1905. except TypeError:
  1906. # if the solid_geometry is a single Polygon the len() will not work
  1907. # in any case, falling here means that we have something in the solid_geometry, even if only
  1908. # a single Polygon, therefore we pass this
  1909. pass
  1910. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1911. # restore GUI to the Selected TAB
  1912. # Remove anything else in the GUI
  1913. self.ui.selected_scroll_area.takeWidget()
  1914. elif edited_obj.kind == 'excellon':
  1915. obj_type = "Excellon"
  1916. self.exc_editor.update_fcexcellon(edited_obj)
  1917. # self.exc_editor.update_options(edited_obj)
  1918. # restore GUI to the Selected TAB
  1919. # Remove anything else in the GUI
  1920. self.ui.tool_scroll_area.takeWidget()
  1921. # delete the old object (the source object) if it was an empty one
  1922. # find if we have drills:
  1923. has_drills = None
  1924. for tt in edited_obj.tools:
  1925. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1926. has_drills = True
  1927. break
  1928. # find if we have slots:
  1929. has_slots = None
  1930. for tt in edited_obj.tools:
  1931. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1932. has_slots = True
  1933. break
  1934. if has_drills is None and has_slots is None:
  1935. old_name = edited_obj.options['name']
  1936. self.collection.delete_by_name(name=old_name)
  1937. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1938. elif edited_obj.kind == 'cncjob':
  1939. obj_type = "CNCJob"
  1940. self.gcode_editor.update_fcgcode(edited_obj)
  1941. # self.exc_editor.update_options(edited_obj)
  1942. # restore GUI to the Selected TAB
  1943. # Remove anything else in the GUI
  1944. self.ui.tool_scroll_area.takeWidget()
  1945. edited_obj.build_ui()
  1946. # close the open tab
  1947. for idx in range(self.ui.plot_tab_area.count()):
  1948. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1949. self.ui.plot_tab_area.closeTab(idx)
  1950. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1951. else:
  1952. self.inform.emit('[WARNING_NOTCL] %s' %
  1953. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1954. return
  1955. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1956. elif response == bt_no:
  1957. # show the Tools Toolbar
  1958. tools_tb = self.ui.toolbartools
  1959. if self.old_state_of_tools_toolbar is True:
  1960. tools_tb.show()
  1961. # clean the Tools Tab
  1962. self.ui.tool_scroll_area.takeWidget()
  1963. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1964. self.ui.notebook.setTabText(2, "Tool")
  1965. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1966. if edited_obj.kind == 'geometry':
  1967. self.geo_editor.deactivate()
  1968. edited_obj.build_ui()
  1969. edited_obj.plot()
  1970. elif edited_obj.kind == 'gerber':
  1971. self.grb_editor.deactivate_grb_editor()
  1972. edited_obj.build_ui()
  1973. elif edited_obj.kind == 'excellon':
  1974. self.exc_editor.deactivate()
  1975. edited_obj.build_ui()
  1976. elif edited_obj.kind == 'cncjob':
  1977. self.gcode_editor.deactivate()
  1978. edited_obj.build_ui()
  1979. # close the open tab
  1980. for idx in range(self.ui.plot_tab_area.count()):
  1981. try:
  1982. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1983. self.ui.plot_tab_area.closeTab(idx)
  1984. except AttributeError:
  1985. continue
  1986. else:
  1987. self.inform.emit('[WARNING_NOTCL] %s' %
  1988. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1989. return
  1990. elif response == bt_cancel:
  1991. return
  1992. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1993. # edited_obj.build_ui()
  1994. # Switch notebook to Selected page
  1995. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1996. else:
  1997. # show the Tools Toolbar
  1998. tools_tb = self.ui.toolbartools
  1999. if self.old_state_of_tools_toolbar is True:
  2000. tools_tb.show()
  2001. if isinstance(edited_obj, GeometryObject):
  2002. self.geo_editor.deactivate()
  2003. elif isinstance(edited_obj, GerberObject):
  2004. self.grb_editor.deactivate_grb_editor()
  2005. elif isinstance(edited_obj, ExcellonObject):
  2006. self.exc_editor.deactivate()
  2007. else:
  2008. self.inform.emit('[WARNING_NOTCL] %s' %
  2009. _("Select a Gerber, Geometry or Excellon Object to update."))
  2010. return
  2011. # if notebook is hidden we show it
  2012. if self.ui.splitter.sizes()[0] == 0:
  2013. self.ui.splitter.setSizes([1, 1])
  2014. # restore the call_source to app
  2015. self.call_source = 'app'
  2016. # edited_obj.plot()
  2017. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2018. self.ui.plot_tab_area.protectTab(0)
  2019. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2020. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2021. self.ui.project_frame.setDisabled(False)
  2022. def get_last_folder(self):
  2023. """
  2024. Get the folder path from where the last file was opened.
  2025. :return: String, last opened folder path
  2026. """
  2027. return self.defaults["global_last_folder"]
  2028. def get_last_save_folder(self):
  2029. """
  2030. Get the folder path from where the last file was saved.
  2031. :return: String, last saved folder path
  2032. """
  2033. loc = self.defaults["global_last_save_folder"]
  2034. if loc is None:
  2035. loc = self.defaults["global_last_folder"]
  2036. if loc is None:
  2037. loc = os.path.dirname(__file__)
  2038. return loc
  2039. @QtCore.pyqtSlot(str)
  2040. @QtCore.pyqtSlot(str, bool)
  2041. def info(self, msg, shell_echo=True):
  2042. """
  2043. Informs the user. Normally on the status bar, optionally
  2044. also on the shell.
  2045. :param msg: Text to write.
  2046. :type msg: str
  2047. :param shell_echo: Control if to display the message msg in the Shell
  2048. :type shell_echo: bool
  2049. :return: None
  2050. """
  2051. # Type of message in brackets at the beginning of the message.
  2052. match = re.search(r"\[(.*)\](.*)", msg)
  2053. if match:
  2054. level = match.group(1)
  2055. msg_ = match.group(2)
  2056. self.ui.fcinfo.set_status(str(msg_), level=level)
  2057. if shell_echo is True:
  2058. if level.lower() == "error":
  2059. self.shell_message(msg, error=True, show=True)
  2060. elif level.lower() == "warning":
  2061. self.shell_message(msg, warning=True, show=True)
  2062. elif level.lower() == "error_notcl":
  2063. self.shell_message(msg, error=True, show=False)
  2064. elif level.lower() == "warning_notcl":
  2065. self.shell_message(msg, warning=True, show=False)
  2066. elif level.lower() == "success":
  2067. self.shell_message(msg, success=True, show=False)
  2068. elif level.lower() == "selected":
  2069. self.shell_message(msg, selected=True, show=False)
  2070. else:
  2071. self.shell_message(msg, show=False)
  2072. else:
  2073. self.ui.fcinfo.set_status(str(msg), level="info")
  2074. # make sure that if the message is to clear the infobar with a space
  2075. # is not printed over and over on the shell
  2076. if msg != '' and shell_echo is True:
  2077. self.shell_message(msg)
  2078. def info_shell(self, msg):
  2079. self.shell_message(msg=msg)
  2080. def on_import_preferences(self):
  2081. """
  2082. Loads the application default settings from a saved file into
  2083. ``self.defaults`` dictionary.
  2084. :return: None
  2085. """
  2086. self.defaults.report_usage("on_import_preferences")
  2087. App.log.debug("App.on_import_preferences()")
  2088. # Show file chooser
  2089. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2090. try:
  2091. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2092. directory=self.data_path,
  2093. filter=filter_)
  2094. except TypeError:
  2095. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2096. filter=filter_)
  2097. filename = str(filename)
  2098. if filename == "":
  2099. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2100. return
  2101. # Load in the defaults from the chosen file
  2102. self.defaults.load(filename=filename)
  2103. self.preferencesUiManager.on_preferences_edited()
  2104. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2105. def on_export_preferences(self):
  2106. """
  2107. Save the defaults dictionary to a file.
  2108. :return: None
  2109. """
  2110. self.defaults.report_usage("on_export_preferences")
  2111. App.log.debug("on_export_preferences()")
  2112. # defaults_file_content = None
  2113. # Show file chooser
  2114. date = str(datetime.today()).rpartition('.')[0]
  2115. date = ''.join(c for c in date if c not in ':-')
  2116. date = date.replace(' ', '_')
  2117. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2118. try:
  2119. filename, _f = FCFileSaveDialog.get_saved_filename(
  2120. caption=_("Export FlatCAM Preferences"),
  2121. directory=self.data_path + '/preferences_' + date,
  2122. ext_filter=filter__
  2123. )
  2124. except TypeError:
  2125. filename, _f = FCFileSaveDialog.get_saved_filename(
  2126. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2127. filename = str(filename)
  2128. if filename == "":
  2129. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2130. return
  2131. # Update options
  2132. self.preferencesUiManager.defaults_read_form()
  2133. self.defaults.propagate_defaults()
  2134. # Save update options
  2135. try:
  2136. self.defaults.write(filename=filename)
  2137. except Exception:
  2138. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2139. return
  2140. if self.defaults["global_open_style"] is False:
  2141. self.file_opened.emit("preferences", filename)
  2142. self.file_saved.emit("preferences", filename)
  2143. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2144. def save_to_file(self, content_to_save, txt_content):
  2145. """
  2146. Save something to a file.
  2147. :return: None
  2148. """
  2149. self.defaults.report_usage("save_to_file")
  2150. App.log.debug("save_to_file()")
  2151. self.date = str(datetime.today()).rpartition('.')[0]
  2152. self.date = ''.join(c for c in self.date if c not in ':-')
  2153. self.date = self.date.replace(' ', '_')
  2154. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2155. path_to_save = self.defaults["global_last_save_folder"] if \
  2156. self.defaults["global_last_save_folder"] is not None else self.data_path
  2157. try:
  2158. filename, _f = FCFileSaveDialog.get_saved_filename(
  2159. caption=_("Save to file"),
  2160. directory=path_to_save + '/file_' + self.date,
  2161. ext_filter=filter__
  2162. )
  2163. except TypeError:
  2164. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2165. filename = str(filename)
  2166. if filename == "":
  2167. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2168. return
  2169. else:
  2170. try:
  2171. with open(filename, 'w') as f:
  2172. ___ = f.read()
  2173. except PermissionError:
  2174. self.inform.emit('[WARNING] %s' %
  2175. _("Permission denied, saving not possible.\n"
  2176. "Most likely another app is holding the file open and not accessible."))
  2177. return
  2178. except IOError:
  2179. App.log.debug('Creating a new file ...')
  2180. f = open(filename, 'w')
  2181. f.close()
  2182. except Exception:
  2183. e = sys.exc_info()[0]
  2184. App.log.error("Could not load the file.")
  2185. App.log.error(str(e))
  2186. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2187. return
  2188. # Save content
  2189. if filename.rpartition('.')[2].lower() == 'html':
  2190. file_content = content_to_save
  2191. else:
  2192. file_content = txt_content
  2193. try:
  2194. with open(filename, "w") as f:
  2195. f.write(file_content)
  2196. except Exception:
  2197. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2198. return
  2199. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2200. def register_recent(self, kind, filename):
  2201. """
  2202. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2203. dictionary.
  2204. :param kind: type of file that was opened
  2205. :param filename: the path and file name for the file that was opened
  2206. :return:
  2207. """
  2208. self.log.debug("register_recent()")
  2209. self.log.debug(" %s" % kind)
  2210. self.log.debug(" %s" % filename)
  2211. record = {'kind': str(kind), 'filename': str(filename)}
  2212. if record in self.recent:
  2213. return
  2214. if record in self.recent_projects:
  2215. return
  2216. if record['kind'] == 'project':
  2217. self.recent_projects.insert(0, record)
  2218. else:
  2219. self.recent.insert(0, record)
  2220. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2221. self.recent.pop()
  2222. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2223. self.recent_projects.pop()
  2224. try:
  2225. f = open(self.data_path + '/recent.json', 'w')
  2226. except IOError:
  2227. App.log.error("Failed to open recent items file for writing.")
  2228. self.inform.emit('[ERROR_NOTCL] %s' %
  2229. _('Failed to open recent files file for writing.'))
  2230. return
  2231. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2232. f.close()
  2233. try:
  2234. fp = open(self.data_path + '/recent_projects.json', 'w')
  2235. except IOError:
  2236. App.log.error("Failed to open recent items file for writing.")
  2237. self.inform.emit('[ERROR_NOTCL] %s' %
  2238. _('Failed to open recent projects file for writing.'))
  2239. return
  2240. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2241. fp.close()
  2242. # Re-build the recent items menu
  2243. self.setup_recent_items()
  2244. def on_about(self):
  2245. """
  2246. Displays the "about" dialog found in the Menu --> Help.
  2247. :return: None
  2248. """
  2249. self.defaults.report_usage("on_about")
  2250. version = self.version
  2251. version_date = self.version_date
  2252. beta = self.beta
  2253. class AboutDialog(QtWidgets.QDialog):
  2254. def __init__(self, app, parent=None):
  2255. QtWidgets.QDialog.__init__(self, parent)
  2256. self.app = app
  2257. # Icon and title
  2258. self.setWindowIcon(parent.app_icon)
  2259. self.setWindowTitle(_("About FlatCAM"))
  2260. self.resize(600, 200)
  2261. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2262. # self.setStyleSheet(
  2263. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2264. # "background-attachment: fixed"
  2265. # )
  2266. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2267. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2268. # palette = QtGui.QPalette()
  2269. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2270. # self.setPalette(palette)
  2271. logo = QtWidgets.QLabel()
  2272. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2273. title = QtWidgets.QLabel(
  2274. "<font size=8><B>FlatCAM</B></font><BR>"
  2275. "{title}<BR>"
  2276. "<BR>"
  2277. "<BR>"
  2278. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2279. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2280. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2281. "<B>{issue}</B></a><BR>".format(
  2282. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2283. devel=_("Development"),
  2284. down=_("DOWNLOAD"),
  2285. issue=_("Issue tracker"))
  2286. )
  2287. title.setOpenExternalLinks(True)
  2288. closebtn = QtWidgets.QPushButton(_("Close"))
  2289. tab_widget = QtWidgets.QTabWidget()
  2290. description_label = QtWidgets.QLabel(
  2291. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2292. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2293. version=version,
  2294. beta=('BETA' if beta else ''),
  2295. date=version_date,
  2296. arch=platform.architecture()[0])
  2297. )
  2298. description_label.setOpenExternalLinks(True)
  2299. lic_lbl_header = QtWidgets.QLabel(
  2300. '%s:<br>%s<br>' % (
  2301. _('Licensed under the MIT license'),
  2302. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2303. "http://www.opensource.org/licenses/mit-license.php</a>"
  2304. )
  2305. )
  2306. lic_lbl_header.setOpenExternalLinks(True)
  2307. lic_lbl_body = QtWidgets.QLabel(
  2308. _(
  2309. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2310. 'of this software and associated documentation files (the "Software"), to deal\n'
  2311. 'in the Software without restriction, including without limitation the rights\n'
  2312. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2313. 'copies of the Software, and to permit persons to whom the Software is\n'
  2314. 'furnished to do so, subject to the following conditions:\n\n'
  2315. 'The above copyright notice and this permission notice shall be included in\n'
  2316. 'all copies or substantial portions of the Software.\n\n'
  2317. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2318. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2319. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2320. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2321. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2322. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2323. 'THE SOFTWARE.'
  2324. )
  2325. )
  2326. attributions_label = QtWidgets.QLabel(
  2327. _(
  2328. 'Some of the icons used are from the following sources:<br>'
  2329. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2330. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2331. 'title="Flaticon">www.flaticon.com</a></div>'
  2332. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2333. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2334. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2335. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2336. 'title="Flaticon">www.flaticon.com</a></div>'
  2337. )
  2338. )
  2339. attributions_label.setOpenExternalLinks(True)
  2340. # layouts
  2341. layout1 = QtWidgets.QVBoxLayout()
  2342. layout1_1 = QtWidgets.QHBoxLayout()
  2343. layout1_2 = QtWidgets.QHBoxLayout()
  2344. layout2 = QtWidgets.QHBoxLayout()
  2345. layout3 = QtWidgets.QHBoxLayout()
  2346. self.setLayout(layout1)
  2347. layout1.addLayout(layout1_1)
  2348. layout1.addLayout(layout1_2)
  2349. layout1.addLayout(layout2)
  2350. layout1.addLayout(layout3)
  2351. layout1_1.addStretch()
  2352. layout1_1.addWidget(description_label)
  2353. layout1_2.addWidget(tab_widget)
  2354. self.splash_tab = QtWidgets.QWidget()
  2355. self.splash_tab.setObjectName("splash_about")
  2356. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2357. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2358. tab_widget.addTab(self.splash_tab, _("Splash"))
  2359. self.programmmers_tab = QtWidgets.QWidget()
  2360. self.programmmers_tab.setObjectName("programmers_about")
  2361. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2362. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2363. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2364. self.translators_tab = QtWidgets.QWidget()
  2365. self.translators_tab.setObjectName("translators_about")
  2366. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2367. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2368. tab_widget.addTab(self.translators_tab, _("Translators"))
  2369. self.license_tab = QtWidgets.QWidget()
  2370. self.license_tab.setObjectName("license_about")
  2371. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2372. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2373. tab_widget.addTab(self.license_tab, _("License"))
  2374. self.attributions_tab = QtWidgets.QWidget()
  2375. self.attributions_tab.setObjectName("attributions_about")
  2376. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2377. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2378. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2379. self.splash_tab_layout.addWidget(logo, stretch=0)
  2380. self.splash_tab_layout.addWidget(title, stretch=1)
  2381. pal = QtGui.QPalette()
  2382. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2383. self.prog_grid_lay = QtWidgets.QGridLayout()
  2384. self.prog_grid_lay.setHorizontalSpacing(20)
  2385. self.prog_grid_lay.setColumnStretch(0, 0)
  2386. self.prog_grid_lay.setColumnStretch(2, 1)
  2387. prog_widget = QtWidgets.QWidget()
  2388. prog_widget.setLayout(self.prog_grid_lay)
  2389. prog_scroll = QtWidgets.QScrollArea()
  2390. prog_scroll.setWidget(prog_widget)
  2391. prog_scroll.setWidgetResizable(True)
  2392. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2393. prog_scroll.setPalette(pal)
  2394. self.programmmers_tab_layout.addWidget(prog_scroll)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2403. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2404. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2405. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2406. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2407. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2408. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2409. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2410. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2411. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2412. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2413. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2414. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2415. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2416. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2417. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2418. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2419. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2420. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2421. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2422. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2423. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2424. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2425. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2426. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2427. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2428. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2429. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2430. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2431. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2432. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2433. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2434. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2435. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2436. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2437. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2438. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2439. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2440. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2441. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2442. self.translator_grid_lay = QtWidgets.QGridLayout()
  2443. self.translator_grid_lay.setColumnStretch(0, 0)
  2444. self.translator_grid_lay.setColumnStretch(1, 0)
  2445. self.translator_grid_lay.setColumnStretch(2, 1)
  2446. self.translator_grid_lay.setColumnStretch(3, 0)
  2447. # trans_widget = QtWidgets.QWidget()
  2448. # trans_widget.setLayout(self.translator_grid_lay)
  2449. # self.translators_tab_layout.addWidget(trans_widget)
  2450. # self.translators_tab_layout.addStretch()
  2451. trans_widget = QtWidgets.QWidget()
  2452. trans_widget.setLayout(self.translator_grid_lay)
  2453. trans_scroll = QtWidgets.QScrollArea()
  2454. trans_scroll.setWidget(trans_widget)
  2455. trans_scroll.setWidgetResizable(True)
  2456. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2457. trans_scroll.setPalette(pal)
  2458. self.translators_tab_layout.addWidget(trans_scroll)
  2459. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2460. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2461. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2462. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2463. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2464. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2465. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2466. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2467. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2468. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2469. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2470. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2471. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2472. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2473. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2474. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2475. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2476. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2477. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2478. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2479. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2480. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2481. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2482. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2483. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2484. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2485. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2486. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2487. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2488. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2489. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2490. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2491. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2492. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2493. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2494. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2495. self.translator_grid_lay.setColumnStretch(0, 0)
  2496. self.translators_tab_layout.addStretch()
  2497. self.license_tab_layout.addWidget(lic_lbl_header)
  2498. self.license_tab_layout.addWidget(lic_lbl_body)
  2499. self.license_tab_layout.addStretch()
  2500. self.attributions_tab_layout.addWidget(attributions_label)
  2501. self.attributions_tab_layout.addStretch()
  2502. layout3.addStretch()
  2503. layout3.addWidget(closebtn)
  2504. closebtn.clicked.connect(self.accept)
  2505. AboutDialog(app=self, parent=self.ui).exec_()
  2506. def on_readme(self):
  2507. """
  2508. Displays the "about" dialog found in the Menu --> Help.
  2509. :return: None
  2510. """
  2511. class ReadmeDialog(QtWidgets.QDialog):
  2512. def __init__(self, app, parent=None):
  2513. QtWidgets.QDialog.__init__(self, parent)
  2514. self.app = app
  2515. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2516. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2517. "<b>click</b></a>"
  2518. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2519. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2520. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2521. # Icon and title
  2522. self.setWindowIcon(parent.app_icon)
  2523. self.setWindowTitle(_("Important Information's"))
  2524. self.resize(750, 375)
  2525. logo = QtWidgets.QLabel()
  2526. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2527. # content = QtWidgets.QLabel(
  2528. # "%s<br>"
  2529. # "%s<br><br>"
  2530. # "%s,<br>"
  2531. # "%s<br>"
  2532. # "<ul>"
  2533. # "<li> &nbsp;%s %s</li>"
  2534. # "<li> &nbsp;%s %s</li>"
  2535. # "</ul>"
  2536. # "%s %s.<br>"
  2537. # "%s"
  2538. # "<ul>"
  2539. # "<li> &nbsp;%s &#128077;</li>"
  2540. # "<li> &nbsp;%s &#128513;</li>"
  2541. # "</ul>" %
  2542. # (
  2543. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2544. # _("Yet it cannot evolve without <b>contributions</b>."),
  2545. # _("If you want to see this application grow and become better and better"),
  2546. # _("you can <b>contribute</b> to the development yourself by:"),
  2547. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2548. # new_features_link,
  2549. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2550. # bugs_link,
  2551. # _("If you like or use this program you can make a donation"),
  2552. # donation_link,
  2553. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2554. # _("it will be welcomed with joy"),
  2555. # _("it will give me a reason to continue")
  2556. # )
  2557. # )
  2558. content = QtWidgets.QLabel(
  2559. "%s<br>"
  2560. "%s<br><br>"
  2561. "%s,<br>"
  2562. "%s<br>"
  2563. "<ul>"
  2564. "<li> &nbsp;%s %s</li>"
  2565. "<li> &nbsp;%s %s</li>"
  2566. "</ul>" %
  2567. (
  2568. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2569. _("Yet it cannot evolve without <b>contributions</b>."),
  2570. _("If you want to see this application grow and become better and better"),
  2571. _("you can <b>contribute</b> to the development yourself by:"),
  2572. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2573. new_features_link,
  2574. _("Bug Reports by providing the steps required to reproduce the bug"),
  2575. bugs_link
  2576. )
  2577. )
  2578. content.setOpenExternalLinks(True)
  2579. # palette
  2580. pal = QtGui.QPalette()
  2581. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2582. # layouts
  2583. main_layout = QtWidgets.QVBoxLayout()
  2584. self.setLayout(main_layout)
  2585. tab_layout = QtWidgets.QHBoxLayout()
  2586. buttons_hlay = QtWidgets.QHBoxLayout()
  2587. main_layout.addLayout(tab_layout)
  2588. main_layout.addLayout(buttons_hlay)
  2589. tab_widget = QtWidgets.QTabWidget()
  2590. tab_layout.addWidget(tab_widget)
  2591. closebtn = QtWidgets.QPushButton(_("Close"))
  2592. buttons_hlay.addStretch()
  2593. buttons_hlay.addWidget(closebtn)
  2594. # CONTRIBUTE section
  2595. self.intro_tab = QtWidgets.QWidget()
  2596. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2597. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2598. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2599. self.grid_lay = QtWidgets.QGridLayout()
  2600. self.grid_lay.setHorizontalSpacing(20)
  2601. self.grid_lay.setColumnStretch(0, 0)
  2602. self.grid_lay.setColumnStretch(1, 1)
  2603. intro_wdg = QtWidgets.QWidget()
  2604. intro_wdg.setLayout(self.grid_lay)
  2605. intro_scroll_area = QtWidgets.QScrollArea()
  2606. intro_scroll_area.setWidget(intro_wdg)
  2607. intro_scroll_area.setWidgetResizable(True)
  2608. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2609. intro_scroll_area.setPalette(pal)
  2610. self.grid_lay.addWidget(logo, 0, 0)
  2611. self.grid_lay.addWidget(content, 0, 1)
  2612. self.intro_tab_layout.addWidget(intro_scroll_area)
  2613. # LINKS EXCHANGE section
  2614. self.links_tab = QtWidgets.QWidget()
  2615. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2616. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2617. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2618. self.links_lay = QtWidgets.QHBoxLayout()
  2619. links_wdg = QtWidgets.QWidget()
  2620. links_wdg.setLayout(self.links_lay)
  2621. links_scroll_area = QtWidgets.QScrollArea()
  2622. links_scroll_area.setWidget(links_wdg)
  2623. links_scroll_area.setWidgetResizable(True)
  2624. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2625. links_scroll_area.setPalette(pal)
  2626. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2627. self.links_tab_layout.addWidget(links_scroll_area)
  2628. # HOW TO section
  2629. self.howto_tab = QtWidgets.QWidget()
  2630. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2631. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2632. tab_widget.addTab(self.howto_tab, _("How To's"))
  2633. self.howto_lay = QtWidgets.QHBoxLayout()
  2634. howto_wdg = QtWidgets.QWidget()
  2635. howto_wdg.setLayout(self.howto_lay)
  2636. howto_scroll_area = QtWidgets.QScrollArea()
  2637. howto_scroll_area.setWidget(howto_wdg)
  2638. howto_scroll_area.setWidgetResizable(True)
  2639. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2640. howto_scroll_area.setPalette(pal)
  2641. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2642. self.howto_tab_layout.addWidget(howto_scroll_area)
  2643. # BUTTONS section
  2644. closebtn.clicked.connect(self.accept)
  2645. ReadmeDialog(app=self, parent=self.ui).exec_()
  2646. def install_bookmarks(self, book_dict=None):
  2647. """
  2648. Install the bookmarks actions in the Help menu -> Bookmarks
  2649. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2650. :return: None
  2651. """
  2652. if book_dict is None:
  2653. self.defaults["global_bookmarks"].update(
  2654. {
  2655. '1': ['FlatCAM', "http://flatcam.org"],
  2656. '2': ['Backup Site', ""]
  2657. }
  2658. )
  2659. else:
  2660. self.defaults["global_bookmarks"].clear()
  2661. self.defaults["global_bookmarks"].update(book_dict)
  2662. # first try to disconnect if somehow they get connected from elsewhere
  2663. for act in self.ui.menuhelp_bookmarks.actions():
  2664. try:
  2665. act.triggered.disconnect()
  2666. except TypeError:
  2667. pass
  2668. # clear all actions except the last one who is the Bookmark manager
  2669. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2670. pass
  2671. else:
  2672. self.ui.menuhelp_bookmarks.removeAction(act)
  2673. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2674. if self.defaults["global_bookmarks"]:
  2675. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2676. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2677. # the JSON is first making the keys as strings (therefore I have to use strings too
  2678. # or do the conversion :(
  2679. # )
  2680. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2681. # the '10' entry jsut after '1' therefore ordering as strings
  2682. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2683. key=lambda x: int(x[0]))
  2684. for entry, bookmark in sorted_bookmarks:
  2685. title = bookmark[0]
  2686. weblink = bookmark[1]
  2687. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2688. act.setText(title)
  2689. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2690. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2691. if title == 'Backup Site' and weblink == "":
  2692. act.triggered.connect(self.on_backup_site)
  2693. else:
  2694. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2695. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2696. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2697. def on_bookmarks_manager(self):
  2698. """
  2699. Adds the bookmark manager in a Tab in Plot Area
  2700. :return:
  2701. """
  2702. for idx in range(self.ui.plot_tab_area.count()):
  2703. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2704. # there can be only one instance of Bookmark Manager at one time
  2705. return
  2706. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2707. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2708. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2709. # add the tab if it was closed
  2710. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2711. # delete the absolute and relative position and messages in the infobar
  2712. # self.ui.position_label.setText("")
  2713. # self.ui.rel_position_label.setText("")
  2714. # hide coordinates toolbars in the infobar while in DB
  2715. self.ui.coords_toolbar.hide()
  2716. self.ui.delta_coords_toolbar.hide()
  2717. # Switch plot_area to preferences page
  2718. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2719. def on_backup_site(self):
  2720. msgbox = QtWidgets.QMessageBox()
  2721. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2722. "1. FlatCAM.org website is down\n"
  2723. "2. Someone forked FlatCAM project and wants to point\n"
  2724. "to his own website\n\n"
  2725. "If you can't get any informations about FlatCAM beta\n"
  2726. "use the YouTube channel link from the Help menu."))
  2727. msgbox.setWindowTitle(_("Alternative website"))
  2728. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2729. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2730. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2731. msgbox.setDefaultButton(bt_yes)
  2732. msgbox.exec_()
  2733. # response = msgbox.clickedButton()
  2734. def on_file_savedefaults(self):
  2735. """
  2736. Callback for menu item File->Save Defaults. Saves application default options
  2737. ``self.defaults`` to current_defaults.FlatConfig.
  2738. :return: None
  2739. """
  2740. self.preferencesUiManager.save_defaults()
  2741. def final_save(self):
  2742. """
  2743. Callback for doing a preferences save to file whenever the application is about to quit.
  2744. If the project has changes, it will ask the user to save the project.
  2745. :return: None
  2746. """
  2747. if self.save_in_progress:
  2748. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2749. return
  2750. if self.should_we_save and self.collection.get_list():
  2751. msgbox = QtWidgets.QMessageBox()
  2752. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2753. "\n"
  2754. "Do you want to Save the project?"))
  2755. msgbox.setWindowTitle(_("Save changes"))
  2756. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2757. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2758. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2759. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2760. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2761. msgbox.setDefaultButton(bt_yes)
  2762. msgbox.exec_()
  2763. response = msgbox.clickedButton()
  2764. if response == bt_yes:
  2765. try:
  2766. self.trayIcon.hide()
  2767. except Exception:
  2768. pass
  2769. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2770. elif response == bt_no:
  2771. try:
  2772. self.trayIcon.hide()
  2773. except Exception:
  2774. pass
  2775. self.quit_application()
  2776. elif response == bt_cancel:
  2777. return
  2778. else:
  2779. try:
  2780. self.trayIcon.hide()
  2781. except Exception:
  2782. pass
  2783. self.quit_application()
  2784. def quit_application(self):
  2785. """
  2786. Called (as a pyslot or not) when the application is quit.
  2787. :return: None
  2788. """
  2789. # close editors before quiting the app, if they are open
  2790. if self.geo_editor.editor_active is True:
  2791. self.geo_editor.deactivate()
  2792. try:
  2793. self.geo_editor.disconnect()
  2794. except TypeError:
  2795. pass
  2796. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2797. if self.exc_editor.editor_active is True:
  2798. self.exc_editor.deactivate()
  2799. try:
  2800. self.grb_editor.disconnect()
  2801. except TypeError:
  2802. pass
  2803. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2804. if self.grb_editor.editor_active is True:
  2805. self.grb_editor.deactivate_grb_editor()
  2806. try:
  2807. self.exc_editor.disconnect()
  2808. except TypeError:
  2809. pass
  2810. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2811. # disconnect the mouse events
  2812. if self.is_legacy:
  2813. self.plotcanvas.graph_event_disconnect(self.mm)
  2814. self.plotcanvas.graph_event_disconnect(self.mp)
  2815. self.plotcanvas.graph_event_disconnect(self.mr)
  2816. self.plotcanvas.graph_event_disconnect(self.mdc)
  2817. self.plotcanvas.graph_event_disconnect(self.kp)
  2818. else:
  2819. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2820. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2821. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2822. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2823. self.on_mouse_double_click_over_plot)
  2824. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2825. self.preferencesUiManager.save_defaults(silent=True)
  2826. log.debug("App.quit_application() --> App Defaults saved.")
  2827. if self.cmd_line_headless != 1:
  2828. # save app state to file
  2829. stgs = QSettings("Open Source", "FlatCAM")
  2830. stgs.setValue('saved_gui_state', self.ui.saveState())
  2831. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2832. stgs.setValue(
  2833. 'language',
  2834. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2835. )
  2836. stgs.setValue(
  2837. 'notebook_font_size',
  2838. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2839. )
  2840. stgs.setValue(
  2841. 'axis_font_size',
  2842. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2843. )
  2844. stgs.setValue(
  2845. 'textbox_font_size',
  2846. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2847. )
  2848. stgs.setValue(
  2849. 'hud_font_size',
  2850. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2851. )
  2852. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2853. stgs.setValue(
  2854. 'machinist',
  2855. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2856. )
  2857. # This will write the setting to the platform specific storage.
  2858. del stgs
  2859. log.debug("App.quit_application() --> App UI state saved.")
  2860. # try to quit the Socket opened by ArgsThread class
  2861. try:
  2862. # self.new_launch.thread_exit = True
  2863. # self.new_launch.listener.close()
  2864. self.new_launch.stop.emit()
  2865. except Exception as err:
  2866. log.debug("App.quit_application() --> %s" % str(err))
  2867. # try to quit the QThread that run ArgsThread class
  2868. try:
  2869. # del self.new_launch
  2870. self.listen_th.quit()
  2871. except Exception as e:
  2872. log.debug("App.quit_application() --> %s" % str(e))
  2873. # terminate workers
  2874. # self.workers.__del__()
  2875. self.clear_pool()
  2876. # quit app by signalling for self.kill_app() method
  2877. # self.close_app_signal.emit()
  2878. QtWidgets.qApp.quit()
  2879. sys.exit(0)
  2880. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2881. # we use the following command
  2882. # minor_v = sys.version_info.minor
  2883. # if minor_v < 8:
  2884. # # make sure that the app closes
  2885. # sys.exit(0)
  2886. # else:
  2887. # os._exit(0) # fix to work with Python 3.8
  2888. @staticmethod
  2889. def kill_app():
  2890. QtWidgets.qApp.quit()
  2891. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2892. # we use the following command
  2893. sys.exit(0)
  2894. def on_portable_checked(self, state):
  2895. """
  2896. Callback called when the checkbox in Preferences GUI is checked.
  2897. It will set the application as portable by creating the preferences and recent files in the
  2898. 'config' folder found in the FlatCAM installation folder.
  2899. :param state: boolean, the state of the checkbox when clicked/checked
  2900. :return:
  2901. """
  2902. line_no = 0
  2903. data = None
  2904. if sys.platform != 'win32':
  2905. # this won't work in Linux or MacOS
  2906. return
  2907. # test if the app was frozen and choose the path for the configuration file
  2908. if getattr(sys, "frozen", False) is True:
  2909. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2910. else:
  2911. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2912. config_file = current_data_path + '\\configuration.txt'
  2913. try:
  2914. with open(config_file, 'r') as f:
  2915. try:
  2916. data = f.readlines()
  2917. except Exception as e:
  2918. log.debug('App.__init__() -->%s' % str(e))
  2919. return
  2920. except FileNotFoundError:
  2921. pass
  2922. for line in data:
  2923. line = line.strip('\n')
  2924. param = str(line).rpartition('=')
  2925. if param[0] == 'portable':
  2926. break
  2927. line_no += 1
  2928. if state:
  2929. data[line_no] = 'portable=True\n'
  2930. # create the new defauults files
  2931. # create current_defaults.FlatConfig file if there is none
  2932. try:
  2933. f = open(current_data_path + '/current_defaults.FlatConfig')
  2934. f.close()
  2935. except IOError:
  2936. App.log.debug('Creating empty current_defaults.FlatConfig')
  2937. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2938. json.dump({}, f)
  2939. f.close()
  2940. # create factory_defaults.FlatConfig file if there is none
  2941. try:
  2942. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2943. f.close()
  2944. except IOError:
  2945. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2946. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2947. json.dump({}, f)
  2948. f.close()
  2949. try:
  2950. f = open(current_data_path + '/recent.json')
  2951. f.close()
  2952. except IOError:
  2953. App.log.debug('Creating empty recent.json')
  2954. f = open(current_data_path + '/recent.json', 'w')
  2955. json.dump([], f)
  2956. f.close()
  2957. try:
  2958. fp = open(current_data_path + '/recent_projects.json')
  2959. fp.close()
  2960. except IOError:
  2961. App.log.debug('Creating empty recent_projects.json')
  2962. fp = open(current_data_path + '/recent_projects.json', 'w')
  2963. json.dump([], fp)
  2964. fp.close()
  2965. # save the current defaults to the new defaults file
  2966. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2967. else:
  2968. data[line_no] = 'portable=False\n'
  2969. with open(config_file, 'w') as f:
  2970. f.writelines(data)
  2971. def on_register_files(self, obj_type=None):
  2972. """
  2973. Called whenever there is a need to register file extensions with FlatCAM.
  2974. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2975. :param obj_type: the type of object to be register for.
  2976. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2977. :return: None
  2978. """
  2979. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2980. new_reg_path = 'Software\\Classes\\'
  2981. # find if the current user is admin
  2982. try:
  2983. is_admin = os.getuid() == 0
  2984. except AttributeError:
  2985. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2986. if is_admin is True:
  2987. root_path = winreg.HKEY_LOCAL_MACHINE
  2988. else:
  2989. root_path = winreg.HKEY_CURRENT_USER
  2990. # create the keys
  2991. def set_reg(name, root_pth, new_reg_path, value):
  2992. try:
  2993. winreg.CreateKey(root_pth, new_reg_path)
  2994. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2995. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2996. return True
  2997. except WindowsError:
  2998. return False
  2999. # delete key in registry
  3000. def delete_reg(root_pth, reg_path, key_to_del):
  3001. key_to_del_path = reg_path + key_to_del
  3002. try:
  3003. winreg.DeleteKey(root_pth, key_to_del_path)
  3004. return True
  3005. except WindowsError:
  3006. return False
  3007. if obj_type is None or obj_type == 'excellon':
  3008. exc_list = \
  3009. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3010. exc_list = [x for x in exc_list if x != '']
  3011. # register all keys in the Preferences window
  3012. for ext in exc_list:
  3013. new_k = new_reg_path + '.%s' % ext
  3014. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3015. # and unregister those that are no longer in the Preferences windows but are in the file
  3016. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3017. if ext not in exc_list:
  3018. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3019. # now write the updated extensions to the self.defaults
  3020. # new_ext = ''
  3021. # for ext in exc_list:
  3022. # new_ext = new_ext + ext + ', '
  3023. # self.defaults["fa_excellon"] = new_ext
  3024. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3025. if obj_type is None or obj_type == 'gcode':
  3026. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3027. gco_list = [x for x in gco_list if x != '']
  3028. # register all keys in the Preferences window
  3029. for ext in gco_list:
  3030. new_k = new_reg_path + '.%s' % ext
  3031. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3032. # and unregister those that are no longer in the Preferences windows but are in the file
  3033. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3034. if ext not in gco_list:
  3035. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3036. # now write the updated extensions to the self.defaults
  3037. # new_ext = ''
  3038. # for ext in gco_list:
  3039. # new_ext = new_ext + ext + ', '
  3040. # self.defaults["fa_gcode"] = new_ext
  3041. self.inform.emit('[success] %s' %
  3042. _("Selected GCode file extensions registered with FlatCAM."))
  3043. if obj_type is None or obj_type == 'gerber':
  3044. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3045. grb_list = [x for x in grb_list if x != '']
  3046. # register all keys in the Preferences window
  3047. for ext in grb_list:
  3048. new_k = new_reg_path + '.%s' % ext
  3049. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3050. # and unregister those that are no longer in the Preferences windows but are in the file
  3051. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3052. if ext not in grb_list:
  3053. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3054. # now write the updated extensions to the self.defaults
  3055. # new_ext = ''
  3056. # for ext in grb_list:
  3057. # new_ext = new_ext + ext + ', '
  3058. # self.defaults["fa_gerber"] = new_ext
  3059. self.inform.emit('[success] %s' %
  3060. _("Selected Gerber file extensions registered with FlatCAM."))
  3061. def add_extension(self, ext_type):
  3062. """
  3063. Add a file extension to the list for a specific object
  3064. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3065. :return:
  3066. """
  3067. if ext_type == 'excellon':
  3068. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3069. if new_ext == '':
  3070. return
  3071. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3072. if new_ext in old_val:
  3073. return
  3074. old_val.append(new_ext)
  3075. old_val.sort()
  3076. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3077. if ext_type == 'gcode':
  3078. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3079. if new_ext == '':
  3080. return
  3081. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3082. if new_ext in old_val:
  3083. return
  3084. old_val.append(new_ext)
  3085. old_val.sort()
  3086. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3087. if ext_type == 'gerber':
  3088. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3089. if new_ext == '':
  3090. return
  3091. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3092. if new_ext in old_val:
  3093. return
  3094. old_val.append(new_ext)
  3095. old_val.sort()
  3096. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3097. if ext_type == 'keyword':
  3098. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3099. if new_kw == '':
  3100. return
  3101. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3102. if new_kw in old_val:
  3103. return
  3104. old_val.append(new_kw)
  3105. old_val.sort()
  3106. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3107. # update the self.myKeywords so the model is updated
  3108. self.autocomplete_kw_list = \
  3109. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3110. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3111. self.shell._edit.set_model_data(self.myKeywords)
  3112. def del_extension(self, ext_type):
  3113. """
  3114. Remove a file extension from the list for a specific object
  3115. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3116. :return:
  3117. """
  3118. if ext_type == 'excellon':
  3119. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3120. if new_ext == '':
  3121. return
  3122. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3123. if new_ext not in old_val:
  3124. return
  3125. old_val.remove(new_ext)
  3126. old_val.sort()
  3127. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3128. if ext_type == 'gcode':
  3129. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3130. if new_ext == '':
  3131. return
  3132. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3133. if new_ext not in old_val:
  3134. return
  3135. old_val.remove(new_ext)
  3136. old_val.sort()
  3137. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3138. if ext_type == 'gerber':
  3139. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3140. if new_ext == '':
  3141. return
  3142. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3143. if new_ext not in old_val:
  3144. return
  3145. old_val.remove(new_ext)
  3146. old_val.sort()
  3147. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3148. if ext_type == 'keyword':
  3149. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3150. if new_kw == '':
  3151. return
  3152. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3153. if new_kw not in old_val:
  3154. return
  3155. old_val.remove(new_kw)
  3156. old_val.sort()
  3157. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3158. # update the self.myKeywords so the model is updated
  3159. self.autocomplete_kw_list = \
  3160. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3161. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3162. self.shell._edit.set_model_data(self.myKeywords)
  3163. def restore_extensions(self, ext_type):
  3164. """
  3165. Restore all file extensions associations with FlatCAM, for a specific object
  3166. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3167. :return:
  3168. """
  3169. if ext_type == 'excellon':
  3170. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3171. # for the ability to open Excellon files with .txt extension
  3172. new_exc_list = deepcopy(self.exc_list)
  3173. try:
  3174. new_exc_list.remove('txt')
  3175. except ValueError:
  3176. pass
  3177. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3178. if ext_type == 'gcode':
  3179. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3180. if ext_type == 'gerber':
  3181. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3182. if ext_type == 'keyword':
  3183. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3184. # update the self.myKeywords so the model is updated
  3185. self.autocomplete_kw_list = self.default_keywords
  3186. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3187. self.shell._edit.set_model_data(self.myKeywords)
  3188. def delete_all_extensions(self, ext_type):
  3189. """
  3190. Delete all file extensions associations with FlatCAM, for a specific object
  3191. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3192. :return:
  3193. """
  3194. if ext_type == 'excellon':
  3195. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3196. if ext_type == 'gcode':
  3197. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3198. if ext_type == 'gerber':
  3199. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3200. if ext_type == 'keyword':
  3201. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3202. # update the self.myKeywords so the model is updated
  3203. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3204. self.shell._edit.set_model_data(self.myKeywords)
  3205. def on_edit_join(self, name=None):
  3206. """
  3207. Callback for Edit->Join. Joins the selected geometry objects into
  3208. a new one.
  3209. :return: None
  3210. """
  3211. self.defaults.report_usage("on_edit_join()")
  3212. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3213. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3214. geo_type_set = set()
  3215. objs = self.collection.get_selected()
  3216. if len(objs) < 2:
  3217. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3218. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3219. return 'fail'
  3220. for obj in objs:
  3221. geo_type_set.add(obj.multigeo)
  3222. # if len(geo_type_list) == 1 means that all list elements are the same
  3223. if len(geo_type_set) != 1:
  3224. self.inform.emit('[ERROR] %s' %
  3225. _("Failed join. The Geometry objects are of different types.\n"
  3226. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3227. "convert from one to another and retry joining \n"
  3228. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3229. "the result may not be what was expected. \n"
  3230. "Check the generated GCODE."))
  3231. return
  3232. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3233. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3234. if True in geo_type_set:
  3235. def initialize(geo_obj, app):
  3236. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3237. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3238. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3239. for v in geo_obj.tools.values():
  3240. v['data']['name'] = obj_name_multi
  3241. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3242. else:
  3243. def initialize(geo_obj, app):
  3244. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3245. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3246. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3247. for v in geo_obj.tools.values():
  3248. v['data']['name'] = obj_name_single
  3249. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3250. self.should_we_save = True
  3251. def on_edit_join_exc(self):
  3252. """
  3253. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3254. a new Excellon.
  3255. :return: None
  3256. """
  3257. self.defaults.report_usage("on_edit_join_exc()")
  3258. objs = self.collection.get_selected()
  3259. for obj in objs:
  3260. if not isinstance(obj, ExcellonObject):
  3261. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3262. return
  3263. if len(objs) < 2:
  3264. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3265. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3266. return 'fail'
  3267. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3268. def initialize(exc_obj, app):
  3269. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3270. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3271. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3272. self.should_we_save = True
  3273. def on_edit_join_grb(self):
  3274. """
  3275. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3276. a new Gerber object.
  3277. :return: None
  3278. """
  3279. self.defaults.report_usage("on_edit_join_grb()")
  3280. objs = self.collection.get_selected()
  3281. for obj in objs:
  3282. if not isinstance(obj, GerberObject):
  3283. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3284. return
  3285. if len(objs) < 2:
  3286. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3287. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3288. return 'fail'
  3289. def initialize(grb_obj, app):
  3290. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3291. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3292. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3293. self.should_we_save = True
  3294. def on_convert_singlegeo_to_multigeo(self):
  3295. """
  3296. Called for converting a Geometry object from single-geo to multi-geo.
  3297. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3298. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3299. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3300. the solid-geometry of that tool.
  3301. :return: None
  3302. """
  3303. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3304. obj = self.collection.get_active()
  3305. if obj is None:
  3306. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3307. return
  3308. if not isinstance(obj, GeometryObject):
  3309. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3310. return
  3311. obj.multigeo = True
  3312. for tooluid, dict_value in obj.tools.items():
  3313. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3314. if not isinstance(obj.solid_geometry, list):
  3315. obj.solid_geometry = [obj.solid_geometry]
  3316. # obj.solid_geometry[:] = []
  3317. obj.plot()
  3318. self.should_we_save = True
  3319. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3320. def on_convert_multigeo_to_singlegeo(self):
  3321. """
  3322. Called for converting a Geometry object from multi-geo to single-geo.
  3323. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3324. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3325. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3326. the solid-geometry of that tool.
  3327. :return: None
  3328. """
  3329. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3330. obj = self.collection.get_active()
  3331. if obj is None:
  3332. self.inform.emit('[ERROR_NOTCL] %s' %
  3333. _("Failed. Select a Geometry Object and try again."))
  3334. return
  3335. if not isinstance(obj, GeometryObject):
  3336. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3337. (_("Expected a GeometryObject, got"), type(obj)))
  3338. return
  3339. obj.multigeo = False
  3340. total_solid_geometry = []
  3341. for tooluid, dict_value in obj.tools.items():
  3342. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3343. # clear the original geometry
  3344. dict_value['solid_geometry'][:] = []
  3345. obj.solid_geometry = deepcopy(total_solid_geometry)
  3346. obj.plot()
  3347. self.should_we_save = True
  3348. self.inform.emit('[success] %s' %
  3349. _("A Geometry object was converted to SingleGeo type."))
  3350. def on_defaults_dict_change(self, field):
  3351. """
  3352. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3353. Edit -> Preferences tab window.
  3354. :param field: the key of the self.defaults dictionary that was changed.
  3355. :return: None
  3356. """
  3357. self.preferencesUiManager.defaults_write_form_field(field=field)
  3358. if field == "units":
  3359. self.set_screen_units(self.defaults['units'])
  3360. def set_screen_units(self, units):
  3361. """
  3362. Set the FlatCAM units on the status bar.
  3363. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3364. :return: None
  3365. """
  3366. self.ui.units_label.setText("[" + units.lower() + "]")
  3367. def on_toggle_units_click(self):
  3368. try:
  3369. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3370. except (TypeError, AttributeError):
  3371. pass
  3372. if self.defaults["units"] == 'MM':
  3373. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3374. else:
  3375. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3376. self.on_toggle_units(no_pref=True)
  3377. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3378. lambda: self.on_toggle_units(no_pref=False))
  3379. def on_toggle_units(self, no_pref=False):
  3380. """
  3381. Callback for the Units radio-button change in the Preferences tab.
  3382. Changes the application's default units adn for the project too.
  3383. If changing the project's units, the change propagates to all of
  3384. the objects in the project.
  3385. :return: None
  3386. """
  3387. self.defaults.report_usage("on_toggle_units")
  3388. if self.toggle_units_ignore:
  3389. return
  3390. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3391. # If option is the same, then ignore
  3392. if new_units == self.defaults["units"].upper():
  3393. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3394. return
  3395. # Keys in self.defaults for which to scale their values
  3396. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3397. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3398. "tools_iso_tool_vtipdia",
  3399. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3400. "gerber_editor_ma_high",
  3401. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3402. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3403. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3404. "excellon_feedrate_probe", "excellon_milling_dia",
  3405. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3406. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3407. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3408. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3409. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3410. "geometry_extracut_length", "geometry_z_pdepth",
  3411. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3412. 'cncjob_tooldia',
  3413. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3414. "tools_paintnewdia",
  3415. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3416. "tools_nccnewdia", "tools_ncc_offset_value",
  3417. "tools_2sided_drilldia",
  3418. "tools_film_boundary", "tools_film_scale_stroke",
  3419. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3420. "tools_cutout_depthperpass",
  3421. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3422. "tools_panelize_spacing_rows",
  3423. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3424. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3425. "tools_transform_buffer_dis",
  3426. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3427. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3428. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3429. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3430. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3431. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3432. "tools_cr_h2h_val", "tools_cr_dh_val",
  3433. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3434. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3435. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3436. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3437. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3438. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3439. "tools_copper_thieving_mask_clearance",
  3440. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3441. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3442. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3443. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3444. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3445. "tools_invert_margin",
  3446. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3447. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3448. def scale_defaults(sfactor):
  3449. for dim in dimensions:
  3450. if dim in [
  3451. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3452. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3453. 'tools_transform_mirror_point'
  3454. ]:
  3455. if self.defaults[dim] is None or self.defaults[dim] == '':
  3456. continue
  3457. try:
  3458. coordinates = self.defaults[dim].split(",")
  3459. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3460. coords_xy[0] *= sfactor
  3461. coords_xy[1] *= sfactor
  3462. self.defaults[dim] = "%.*f, %.*f" % (
  3463. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3464. except Exception as e:
  3465. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3466. elif dim in [
  3467. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3468. ]:
  3469. if self.defaults[dim] is None or self.defaults[dim] == '':
  3470. continue
  3471. try:
  3472. self.defaults[dim] = float(self.defaults[dim])
  3473. tools_diameters = [self.defaults[dim]]
  3474. except ValueError:
  3475. try:
  3476. tools_string = self.defaults[dim].split(",")
  3477. tools_diameters = [eval(a) for a in tools_string if a != '']
  3478. except Exception as e:
  3479. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3480. continue
  3481. self.defaults[dim] = ''
  3482. td_len = len(tools_diameters)
  3483. if td_len > 1:
  3484. for t in range(td_len):
  3485. tools_diameters[t] *= sfactor
  3486. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3487. else:
  3488. tools_diameters[0] *= sfactor
  3489. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3490. elif dim in ['global_gridx', 'global_gridy']:
  3491. # format the number of decimals to the one specified in self.decimals
  3492. try:
  3493. val = float(self.defaults[dim]) * sfactor
  3494. except Exception as e:
  3495. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3496. continue
  3497. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3498. else:
  3499. # the number of decimals for the rest is kept unchanged
  3500. if self.defaults[dim]:
  3501. try:
  3502. val = float(self.defaults[dim]) * sfactor
  3503. except Exception as e:
  3504. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3505. continue
  3506. self.defaults[dim] = val
  3507. # The scaling factor depending on choice of units.
  3508. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3509. # Changing project units. Warn user.
  3510. msgbox = QtWidgets.QMessageBox()
  3511. msgbox.setWindowTitle(_("Toggle Units"))
  3512. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3513. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3514. msgbox.setText(_("Changing the units of the project\n"
  3515. "will scale all objects.\n\n"
  3516. "Do you want to continue?"))
  3517. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3518. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3519. msgbox.setDefaultButton(bt_ok)
  3520. msgbox.exec_()
  3521. response = msgbox.clickedButton()
  3522. if response == bt_ok:
  3523. if no_pref is False:
  3524. self.preferencesUiManager.defaults_read_form()
  3525. scale_defaults(factor)
  3526. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3527. self.defaults["units"] = new_units
  3528. # update the defaults from form, some may assume that the conversion is enough and it's not
  3529. self.on_options_app2project()
  3530. # update the objects
  3531. for obj in self.collection.get_list():
  3532. obj.convert_units(new_units)
  3533. # make that the properties stored in the object are also updated
  3534. self.app_obj.object_changed.emit(obj)
  3535. # rebuild the object UI
  3536. obj.build_ui()
  3537. # change this only if the workspace is active
  3538. if self.defaults['global_workspace'] is True:
  3539. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3540. # adjust the grid values on the main toolbar
  3541. val_x = float(self.defaults['global_gridx']) * factor
  3542. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3543. current = self.collection.get_active()
  3544. if current is not None:
  3545. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3546. if not isinstance(current, GeometryObject):
  3547. current.to_form()
  3548. # replot all objects
  3549. self.plot_all()
  3550. # set the status labels to reflect the current FlatCAM units
  3551. self.set_screen_units(new_units)
  3552. # signal to the app that we changed the object properties and it should save the project
  3553. self.should_we_save = True
  3554. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3555. else:
  3556. # Undo toggling
  3557. self.toggle_units_ignore = True
  3558. if self.defaults['units'].upper() == 'MM':
  3559. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3560. else:
  3561. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3562. self.toggle_units_ignore = False
  3563. # store the grid values so they are not changed in the next step
  3564. val_x = float(self.defaults['global_gridx'])
  3565. val_y = float(self.defaults['global_gridy'])
  3566. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3567. self.preferencesUiManager.defaults_read_form()
  3568. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3569. # in self.defaults from the GUI elements but
  3570. # I don't want it for the grid values, so I update them here
  3571. self.defaults['global_gridx'] = val_x
  3572. self.defaults['global_gridy'] = val_y
  3573. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3574. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3575. def on_deselect_all(self):
  3576. self.collection.set_all_inactive()
  3577. self.delete_selection_shape()
  3578. def on_workspace_modified(self):
  3579. # self.save_defaults(silent=True)
  3580. self.plotcanvas.delete_workspace()
  3581. self.preferencesUiManager.defaults_read_form()
  3582. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3583. def on_workspace(self):
  3584. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3585. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3586. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3587. else:
  3588. self.plotcanvas.delete_workspace()
  3589. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3590. self.preferencesUiManager.defaults_read_form()
  3591. # self.save_defaults(silent=True)
  3592. def on_workspace_toggle(self):
  3593. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3594. try:
  3595. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3596. except TypeError:
  3597. pass
  3598. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3599. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3600. self.on_workspace()
  3601. def on_cursor_type(self, val):
  3602. """
  3603. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3604. :return: None
  3605. """
  3606. self.app_cursor.enabled = False
  3607. if val == 'small':
  3608. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3609. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3610. self.app_cursor = self.plotcanvas.new_cursor()
  3611. else:
  3612. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3613. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3614. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3615. if self.ui.grid_snap_btn.isChecked():
  3616. self.app_cursor.enabled = True
  3617. else:
  3618. self.app_cursor.enabled = False
  3619. def on_tool_add_keypress(self):
  3620. # ## Current application units in Upper Case
  3621. self.units = self.defaults['units'].upper()
  3622. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3623. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3624. if notebook_widget_name == 'selected_tab':
  3625. if self.collection.get_active().kind == 'geometry':
  3626. # Tool add works for Geometry only if Advanced is True in Preferences
  3627. if self.defaults["global_app_level"] == 'a':
  3628. tool_add_popup = FCInputDialog(title="New Tool ...",
  3629. text='Enter a Tool Diameter:',
  3630. min=0.0000, max=99.9999, decimals=4)
  3631. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3632. val, ok = tool_add_popup.get_value()
  3633. if ok:
  3634. if float(val) == 0:
  3635. self.inform.emit('[WARNING_NOTCL] %s' %
  3636. _("Please enter a tool diameter with non-zero value, in Float format."))
  3637. return
  3638. self.collection.get_active().on_tool_add(dia=float(val))
  3639. else:
  3640. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3641. else:
  3642. msgbox = QtWidgets.QMessageBox()
  3643. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3644. "Go to Preferences -> General - Show Advanced Options."))
  3645. msgbox.setWindowTitle("Tool adding ...")
  3646. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3647. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3648. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3649. msgbox.setDefaultButton(bt_ok)
  3650. msgbox.exec_()
  3651. # work only if the notebook tab on focus is the Tools_Tab
  3652. if notebook_widget_name == 'tool_tab':
  3653. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3654. # and only if the tool is NCC Tool
  3655. if tool_widget == self.ncclear_tool.toolName:
  3656. self.ncclear_tool.on_add_tool_by_key()
  3657. # and only if the tool is Paint Area Tool
  3658. elif tool_widget == self.paint_tool.toolName:
  3659. self.paint_tool.on_add_tool_by_key()
  3660. # and only if the tool is Solder Paste Dispensing Tool
  3661. elif tool_widget == self.paste_tool.toolName:
  3662. self.paste_tool.on_add_tool_by_key()
  3663. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3664. # See description below.
  3665. def on_delete_keypress(self):
  3666. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3667. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3668. if notebook_widget_name == 'selected_tab':
  3669. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3670. self.collection.get_active().on_tool_delete()
  3671. # work only if the notebook tab on focus is the Tools_Tab
  3672. elif notebook_widget_name == 'tool_tab':
  3673. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3674. # and only if the tool is NCC Tool
  3675. if tool_widget == self.ncclear_tool.toolName:
  3676. self.ncclear_tool.on_tool_delete()
  3677. # and only if the tool is Paint Tool
  3678. elif tool_widget == self.paint_tool.toolName:
  3679. self.paint_tool.on_tool_delete()
  3680. # and only if the tool is Solder Paste Dispensing Tool
  3681. elif tool_widget == self.paste_tool.toolName:
  3682. self.paste_tool.on_tool_delete()
  3683. # and only if the tool is Isolation Tool
  3684. elif tool_widget == self.isolation_tool.toolName:
  3685. self.isolation_tool.on_tool_delete()
  3686. else:
  3687. self.on_delete()
  3688. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3689. # some screens you have to be careful where you hover with your mouse.
  3690. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3691. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3692. # Complicated, I know :)
  3693. def on_delete(self, force_deletion=False):
  3694. """
  3695. Delete the currently selected FlatCAMObjs.
  3696. :param force_deletion: used by Tcl command
  3697. :return: None
  3698. """
  3699. self.defaults.report_usage("on_delete()")
  3700. response = None
  3701. bt_ok = None
  3702. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3703. # a geometry object before we update it.
  3704. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3705. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3706. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3707. msgbox = QtWidgets.QMessageBox()
  3708. msgbox.setWindowTitle(_("Delete objects"))
  3709. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3710. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3711. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3712. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3713. "the selected objects?"))
  3714. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3715. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3716. msgbox.setDefaultButton(bt_ok)
  3717. msgbox.exec_()
  3718. response = msgbox.clickedButton()
  3719. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3720. response = bt_ok
  3721. if response == bt_ok:
  3722. if self.collection.get_active():
  3723. self.log.debug("App.on_delete()")
  3724. for obj_active in self.collection.get_selected():
  3725. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3726. if obj_active.kind == 'gerber':
  3727. obj_active.mark_shapes_storage.clear()
  3728. obj_active.mark_shapes.clear(update=True)
  3729. obj_active.mark_shapes.enabled = False
  3730. elif obj_active.kind == 'cncjob':
  3731. try:
  3732. obj_active.text_col.enabled = False
  3733. del obj_active.text_col
  3734. obj_active.annotation.clear(update=True)
  3735. del obj_active.annotation
  3736. except AttributeError as e:
  3737. log.debug(
  3738. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3739. )
  3740. while self.collection.get_selected():
  3741. self.delete_first_selected()
  3742. # make sure that the selection shape is deleted, too
  3743. self.delete_selection_shape()
  3744. # if there are no longer objects delete also the exclusion areas shapes
  3745. if not self.collection.get_list():
  3746. self.exc_areas.clear_shapes()
  3747. self.inform.emit('%s...' % _("Object(s) deleted"))
  3748. else:
  3749. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3750. else:
  3751. self.inform.emit(_("Save the work in Editor and try again ..."))
  3752. def delete_first_selected(self):
  3753. # Keep this for later
  3754. try:
  3755. sel_obj = self.collection.get_active()
  3756. name = sel_obj.options["name"]
  3757. isPlotted = sel_obj.options["plot"]
  3758. except AttributeError:
  3759. self.log.debug("Nothing selected for deletion")
  3760. return
  3761. if self.is_legacy is True:
  3762. # Remove plot only if the object was plotted otherwise delaxes will fail
  3763. if isPlotted:
  3764. try:
  3765. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3766. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3767. except Exception as e:
  3768. log.debug("App.delete_first_selected() --> %s" % str(e))
  3769. self.plotcanvas.auto_adjust_axes()
  3770. # Remove from dictionary
  3771. self.collection.delete_active()
  3772. # Clear form
  3773. self.setup_component_editor()
  3774. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3775. def on_set_origin(self):
  3776. """
  3777. Set the origin to the left mouse click position
  3778. :return: None
  3779. """
  3780. # display the message for the user
  3781. # and ask him to click on the desired position
  3782. self.defaults.report_usage("on_set_origin()")
  3783. def origin_replot():
  3784. def worker_task():
  3785. with self.proc_container.new('%s...' % _("Plotting")):
  3786. for obj in self.collection.get_list():
  3787. obj.plot()
  3788. self.plotcanvas.fit_view()
  3789. if self.is_legacy:
  3790. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3791. else:
  3792. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3793. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3794. self.inform.emit(_('Click to set the origin ...'))
  3795. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3796. # first disconnect it as it may have been used by something else
  3797. try:
  3798. self.replot_signal.disconnect()
  3799. except TypeError:
  3800. pass
  3801. self.replot_signal[list].connect(origin_replot)
  3802. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3803. """
  3804. :param event:
  3805. :param location:
  3806. :param noplot:
  3807. :param use_thread:
  3808. :return:
  3809. """
  3810. noplot_sig = noplot
  3811. def worker_task():
  3812. with self.proc_container.new(_("Setting Origin...")):
  3813. obj_list = self.collection.get_list()
  3814. for obj in obj_list:
  3815. obj.offset((x, y))
  3816. self.app_obj.object_changed.emit(obj)
  3817. # Update the object bounding box options
  3818. a, b, c, d = obj.bounds()
  3819. obj.options['xmin'] = a
  3820. obj.options['ymin'] = b
  3821. obj.options['xmax'] = c
  3822. obj.options['ymax'] = d
  3823. self.inform.emit('[success] %s...' % _('Origin set'))
  3824. for obj in obj_list:
  3825. out_name = obj.options["name"]
  3826. if obj.kind == 'gerber':
  3827. obj.source_file = self.export_gerber(
  3828. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3829. elif obj.kind == 'excellon':
  3830. obj.source_file = self.export_excellon(
  3831. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3832. if noplot_sig is False:
  3833. self.replot_signal.emit([])
  3834. if location is not None:
  3835. if len(location) != 2:
  3836. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3837. return 'fail'
  3838. x, y = location
  3839. if use_thread is True:
  3840. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3841. else:
  3842. worker_task()
  3843. self.should_we_save = True
  3844. return
  3845. if event is not None and event.button == 1:
  3846. if self.is_legacy is False:
  3847. event_pos = event.pos
  3848. else:
  3849. event_pos = (event.xdata, event.ydata)
  3850. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3851. if self.grid_status():
  3852. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3853. else:
  3854. pos = pos_canvas
  3855. x = 0 - pos[0]
  3856. y = 0 - pos[1]
  3857. if use_thread is True:
  3858. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3859. else:
  3860. worker_task()
  3861. self.should_we_save = True
  3862. def on_move2origin(self, use_thread=True):
  3863. """
  3864. Move selected objects to origin.
  3865. :param use_thread: Control if to use threaded operation. Boolean.
  3866. :return:
  3867. """
  3868. def worker_task():
  3869. with self.proc_container.new(_("Moving to Origin...")):
  3870. obj_list = self.collection.get_selected()
  3871. if not obj_list:
  3872. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3873. return
  3874. xminlist = []
  3875. yminlist = []
  3876. # first get a bounding box to fit all
  3877. for obj in obj_list:
  3878. xmin, ymin, xmax, ymax = obj.bounds()
  3879. xminlist.append(xmin)
  3880. yminlist.append(ymin)
  3881. # get the minimum x,y for all objects selected
  3882. x = min(xminlist)
  3883. y = min(yminlist)
  3884. for obj in obj_list:
  3885. obj.offset((-x, -y))
  3886. self.app_obj.object_changed.emit(obj)
  3887. # Update the object bounding box options
  3888. a, b, c, d = obj.bounds()
  3889. obj.options['xmin'] = a
  3890. obj.options['ymin'] = b
  3891. obj.options['xmax'] = c
  3892. obj.options['ymax'] = d
  3893. for obj in obj_list:
  3894. obj.plot()
  3895. for obj in obj_list:
  3896. out_name = obj.options["name"]
  3897. if obj.kind == 'gerber':
  3898. obj.source_file = self.export_gerber(
  3899. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3900. elif obj.kind == 'excellon':
  3901. obj.source_file = self.export_excellon(
  3902. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3903. self.inform.emit('[success] %s...' % _('Origin set'))
  3904. if use_thread is True:
  3905. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3906. else:
  3907. worker_task()
  3908. self.should_we_save = True
  3909. def on_jump_to(self, custom_location=None, fit_center=True):
  3910. """
  3911. Jump to a location by setting the mouse cursor location.
  3912. :param custom_location: Jump to a specified point. (x, y) tuple.
  3913. :param fit_center: If to fit view. Boolean.
  3914. :return:
  3915. """
  3916. self.defaults.report_usage("on_jump_to()")
  3917. if not custom_location:
  3918. dia_box_location = None
  3919. try:
  3920. dia_box_location = eval(self.clipboard.text())
  3921. except Exception:
  3922. pass
  3923. if type(dia_box_location) == tuple:
  3924. dia_box_location = str(dia_box_location)
  3925. else:
  3926. dia_box_location = None
  3927. # dia_box = Dialog_box(title=_("Jump to ..."),
  3928. # label=_("Enter the coordinates in format X,Y:"),
  3929. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3930. # initial_text=dia_box_location)
  3931. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3932. label=_("Enter the coordinates in format X,Y:"),
  3933. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3934. initial_text=dia_box_location,
  3935. reference=self.defaults['global_jump_ref'])
  3936. if dia_box.ok is True:
  3937. try:
  3938. location = eval(dia_box.location)
  3939. if not isinstance(location, tuple):
  3940. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3941. return
  3942. if dia_box.reference == 'rel':
  3943. rel_x = self.mouse[0] + location[0]
  3944. rel_y = self.mouse[1] + location[1]
  3945. location = (rel_x, rel_y)
  3946. self.defaults['global_jump_ref'] = dia_box.reference
  3947. except Exception:
  3948. return
  3949. else:
  3950. return
  3951. else:
  3952. location = custom_location
  3953. self.jump_signal.emit(location)
  3954. if fit_center:
  3955. self.plotcanvas.fit_center(loc=location)
  3956. cursor = QtGui.QCursor()
  3957. if self.is_legacy is False:
  3958. # I don't know where those differences come from but they are constant for the current
  3959. # execution of the application and they are multiples of a value around 0.0263mm.
  3960. # In a random way sometimes they are more sometimes they are less
  3961. # if units == 'MM':
  3962. # cal_factor = 0.0263
  3963. # else:
  3964. # cal_factor = 0.0263 / 25.4
  3965. cal_location = (location[0], location[1])
  3966. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3967. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3968. j_pos = (
  3969. int(canvas_origin.x() + round(jump_loc[0])),
  3970. int(canvas_origin.y() + round(jump_loc[1]))
  3971. )
  3972. cursor.setPos(j_pos[0], j_pos[1])
  3973. else:
  3974. # find the canvas origin which is in the top left corner
  3975. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3976. # determine the coordinates for the lowest left point of the canvas
  3977. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3978. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3979. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3980. # canvas) and the point (width, height) is in the top-right location
  3981. loc = self.plotcanvas.axes.transData.transform_point(location)
  3982. j_pos = (
  3983. int(x0 + loc[0]),
  3984. int(y0 - loc[1])
  3985. )
  3986. cursor.setPos(j_pos[0], j_pos[1])
  3987. self.plotcanvas.mouse = [location[0], location[1]]
  3988. if self.defaults["global_cursor_color_enabled"] is True:
  3989. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3990. else:
  3991. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3992. if self.grid_status():
  3993. # Update cursor
  3994. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3995. symbol='++', edge_color=self.cursor_color_3D,
  3996. edge_width=self.defaults["global_cursor_width"],
  3997. size=self.defaults["global_cursor_size"])
  3998. # Set the relative position label
  3999. dx = location[0] - float(self.rel_point1[0])
  4000. dy = location[1] - float(self.rel_point1[1])
  4001. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4002. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4003. # Set the position label
  4004. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4005. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4006. units = self.defaults["units"].lower()
  4007. self.plotcanvas.text_hud.text = \
  4008. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4009. dx, units, dy, units, location[0], units, location[1], units)
  4010. self.inform.emit('[success] %s' % _("Done."))
  4011. return location
  4012. def on_locate(self, obj, fit_center=True):
  4013. """
  4014. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4015. :param obj: The object on which to locate certain points
  4016. :param fit_center: If to fit view. Boolean.
  4017. :return: A point location. (x, y) tuple.
  4018. """
  4019. self.defaults.report_usage("on_locate()")
  4020. if obj is None:
  4021. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4022. return 'fail'
  4023. class DialogBoxChoice(QtWidgets.QDialog):
  4024. def __init__(self, title=None, icon=None, choice='bl'):
  4025. """
  4026. :param title: string with the window title
  4027. """
  4028. super(DialogBoxChoice, self).__init__()
  4029. self.ok = False
  4030. self.setWindowIcon(icon)
  4031. self.setWindowTitle(str(title))
  4032. self.form = QtWidgets.QFormLayout(self)
  4033. self.ref_radio = RadioSet([
  4034. {"label": _("Bottom-Left"), "value": "bl"},
  4035. {"label": _("Top-Left"), "value": "tl"},
  4036. {"label": _("Bottom-Right"), "value": "br"},
  4037. {"label": _("Top-Right"), "value": "tr"},
  4038. {"label": _("Center"), "value": "c"}
  4039. ], orientation='vertical', stretch=False)
  4040. self.ref_radio.set_value(choice)
  4041. self.form.addRow(self.ref_radio)
  4042. self.button_box = QtWidgets.QDialogButtonBox(
  4043. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4044. Qt.Horizontal, parent=self)
  4045. self.form.addRow(self.button_box)
  4046. self.button_box.accepted.connect(self.accept)
  4047. self.button_box.rejected.connect(self.reject)
  4048. if self.exec_() == QtWidgets.QDialog.Accepted:
  4049. self.ok = True
  4050. self.location_point = self.ref_radio.get_value()
  4051. else:
  4052. self.ok = False
  4053. self.location_point = None
  4054. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4055. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4056. choice=self.defaults['global_locate_pt'])
  4057. if dia_box.ok is True:
  4058. try:
  4059. location_point = dia_box.location_point
  4060. self.defaults['global_locate_pt'] = dia_box.location_point
  4061. except Exception:
  4062. return
  4063. else:
  4064. return
  4065. loc_b = obj.bounds()
  4066. if location_point == 'bl':
  4067. location = (loc_b[0], loc_b[1])
  4068. elif location_point == 'tl':
  4069. location = (loc_b[0], loc_b[3])
  4070. elif location_point == 'br':
  4071. location = (loc_b[2], loc_b[1])
  4072. elif location_point == 'tr':
  4073. location = (loc_b[2], loc_b[3])
  4074. else:
  4075. # center
  4076. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4077. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4078. location = (cx, cy)
  4079. self.locate_signal.emit(location, location_point)
  4080. if fit_center:
  4081. self.plotcanvas.fit_center(loc=location)
  4082. cursor = QtGui.QCursor()
  4083. if self.is_legacy is False:
  4084. # I don't know where those differences come from but they are constant for the current
  4085. # execution of the application and they are multiples of a value around 0.0263mm.
  4086. # In a random way sometimes they are more sometimes they are less
  4087. # if units == 'MM':
  4088. # cal_factor = 0.0263
  4089. # else:
  4090. # cal_factor = 0.0263 / 25.4
  4091. cal_location = (location[0], location[1])
  4092. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4093. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4094. j_pos = (
  4095. int(canvas_origin.x() + round(jump_loc[0])),
  4096. int(canvas_origin.y() + round(jump_loc[1]))
  4097. )
  4098. cursor.setPos(j_pos[0], j_pos[1])
  4099. else:
  4100. # find the canvas origin which is in the top left corner
  4101. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4102. # determine the coordinates for the lowest left point of the canvas
  4103. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4104. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4105. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4106. # canvas) and the point (width, height) is in the top-right location
  4107. loc = self.plotcanvas.axes.transData.transform_point(location)
  4108. j_pos = (
  4109. int(x0 + loc[0]),
  4110. int(y0 - loc[1])
  4111. )
  4112. cursor.setPos(j_pos[0], j_pos[1])
  4113. self.plotcanvas.mouse = [location[0], location[1]]
  4114. if self.defaults["global_cursor_color_enabled"] is True:
  4115. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4116. else:
  4117. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4118. if self.grid_status():
  4119. # Update cursor
  4120. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4121. symbol='++', edge_color=self.cursor_color_3D,
  4122. edge_width=self.defaults["global_cursor_width"],
  4123. size=self.defaults["global_cursor_size"])
  4124. # Set the relative position label
  4125. self.dx = location[0] - float(self.rel_point1[0])
  4126. self.dy = location[1] - float(self.rel_point1[1])
  4127. # Set the position label
  4128. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4129. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4130. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4131. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4132. units = self.defaults["units"].lower()
  4133. self.plotcanvas.text_hud.text = \
  4134. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4135. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4136. self.inform.emit('[success] %s' % _("Done."))
  4137. return location
  4138. def on_copy_command(self):
  4139. """
  4140. Will copy a selection of objects, creating new objects.
  4141. :return:
  4142. """
  4143. self.defaults.report_usage("on_copy_command()")
  4144. def initialize(obj_init, app):
  4145. """
  4146. :param obj_init: the new object
  4147. :type obj_init: class
  4148. :param app: An instance of the App class
  4149. :type app: App
  4150. :return: None
  4151. :rtype:
  4152. """
  4153. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4154. try:
  4155. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4156. except AttributeError:
  4157. pass
  4158. try:
  4159. obj_init.apertures = deepcopy(obj.apertures)
  4160. except AttributeError:
  4161. pass
  4162. try:
  4163. if obj.tools:
  4164. obj_init.tools = deepcopy(obj.tools)
  4165. except Exception as err:
  4166. log.debug("App.on_copy_command() --> %s" % str(err))
  4167. try:
  4168. obj_init.source_file = deepcopy(obj.source_file)
  4169. except (AttributeError, TypeError):
  4170. pass
  4171. def initialize_excellon(obj_init, app):
  4172. obj_init.source_file = deepcopy(obj.source_file)
  4173. obj_init.tools = deepcopy(obj.tools)
  4174. # drills are offset, so they need to be deep copied
  4175. obj_init.drills = deepcopy(obj.drills)
  4176. # slots are offset, so they need to be deep copied
  4177. obj_init.slots = deepcopy(obj.slots)
  4178. obj_init.create_geometry()
  4179. def initialize_script(obj_init, app_obj):
  4180. obj_init.source_file = deepcopy(obj.source_file)
  4181. def initialize_document(obj_init, app_obj):
  4182. obj_init.source_file = deepcopy(obj.source_file)
  4183. for obj in self.collection.get_selected():
  4184. obj_name = obj.options["name"]
  4185. try:
  4186. if isinstance(obj, ExcellonObject):
  4187. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4188. elif isinstance(obj, GerberObject):
  4189. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4190. elif isinstance(obj, GeometryObject):
  4191. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4192. elif isinstance(obj, ScriptObject):
  4193. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4194. elif isinstance(obj, DocumentObject):
  4195. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4196. except Exception as e:
  4197. return "Operation failed: %s" % str(e)
  4198. def on_copy_object2(self, custom_name):
  4199. def initialize_geometry(obj_init, app):
  4200. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4201. try:
  4202. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4203. except AttributeError:
  4204. pass
  4205. try:
  4206. obj_init.apertures = deepcopy(obj.apertures)
  4207. except AttributeError:
  4208. pass
  4209. try:
  4210. if obj.tools:
  4211. obj_init.tools = deepcopy(obj.tools)
  4212. except Exception as ee:
  4213. log.debug("on_copy_object2() --> %s" % str(ee))
  4214. def initialize_gerber(obj_init, app):
  4215. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4216. obj_init.apertures = deepcopy(obj.apertures)
  4217. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4218. def initialize_excellon(obj_init, app):
  4219. obj_init.tools = deepcopy(obj.tools)
  4220. # drills are offset, so they need to be deep copied
  4221. obj_init.drills = deepcopy(obj.drills)
  4222. # slots are offset, so they need to be deep copied
  4223. obj_init.slots = deepcopy(obj.slots)
  4224. obj_init.create_geometry()
  4225. for obj in self.collection.get_selected():
  4226. obj_name = obj.options["name"]
  4227. try:
  4228. if isinstance(obj, ExcellonObject):
  4229. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4230. elif isinstance(obj, GerberObject):
  4231. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4232. elif isinstance(obj, GeometryObject):
  4233. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4234. except Exception as er:
  4235. return "Operation failed: %s" % str(er)
  4236. def on_rename_object(self, text):
  4237. """
  4238. Will rename an object.
  4239. :param text: New name for the object.
  4240. :return:
  4241. """
  4242. self.defaults.report_usage("on_rename_object()")
  4243. named_obj = self.collection.get_active()
  4244. for obj in named_obj:
  4245. if obj is list:
  4246. self.on_rename_object(text)
  4247. else:
  4248. try:
  4249. obj.options['name'] = text
  4250. except Exception as e:
  4251. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4252. def convert_any2geo(self):
  4253. """
  4254. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4255. :return:
  4256. """
  4257. self.defaults.report_usage("convert_any2geo()")
  4258. def initialize(obj_init, app):
  4259. obj_init.solid_geometry = obj.solid_geometry
  4260. try:
  4261. obj_init.follow_geometry = obj.follow_geometry
  4262. except AttributeError:
  4263. pass
  4264. try:
  4265. obj_init.apertures = obj.apertures
  4266. except AttributeError:
  4267. pass
  4268. try:
  4269. if obj.tools:
  4270. obj_init.tools = obj.tools
  4271. except AttributeError:
  4272. pass
  4273. def initialize_excellon(obj_init, app):
  4274. # objs = self.collection.get_selected()
  4275. # GeometryObject.merge(objs, obj)
  4276. solid_geo = []
  4277. for tool in obj.tools:
  4278. for geo in obj.tools[tool]['solid_geometry']:
  4279. solid_geo.append(geo)
  4280. obj_init.solid_geometry = deepcopy(solid_geo)
  4281. if not self.collection.get_selected():
  4282. log.warning("App.convert_any2geo --> No object selected")
  4283. self.inform.emit('[WARNING_NOTCL] %s' %
  4284. _("No object is selected. Select an object and try again."))
  4285. return
  4286. for obj in self.collection.get_selected():
  4287. obj_name = obj.options["name"]
  4288. try:
  4289. if obj.kind == 'excellon':
  4290. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4291. else:
  4292. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4293. except Exception as e:
  4294. return "Operation failed: %s" % str(e)
  4295. def convert_any2gerber(self):
  4296. """
  4297. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4298. :return:
  4299. """
  4300. def initialize_geometry(obj_init, app):
  4301. apertures = {}
  4302. apid = 0
  4303. apertures[str(apid)] = {}
  4304. apertures[str(apid)]['geometry'] = []
  4305. for obj_orig in obj.solid_geometry:
  4306. new_elem = {}
  4307. new_elem['solid'] = obj_orig
  4308. try:
  4309. new_elem['follow'] = obj_orig.exterior
  4310. except AttributeError:
  4311. pass
  4312. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4313. apertures[str(apid)]['size'] = 0.0
  4314. apertures[str(apid)]['type'] = 'C'
  4315. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4316. obj_init.apertures = deepcopy(apertures)
  4317. def initialize_excellon(obj_init, app):
  4318. apertures = {}
  4319. apid = 10
  4320. for tool in obj.tools:
  4321. apertures[str(apid)] = {}
  4322. apertures[str(apid)]['geometry'] = []
  4323. for geo in obj.tools[tool]['solid_geometry']:
  4324. new_el = {}
  4325. new_el['solid'] = geo
  4326. new_el['follow'] = geo.exterior
  4327. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4328. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4329. apertures[str(apid)]['type'] = 'C'
  4330. apid += 1
  4331. # create solid_geometry
  4332. solid_geometry = []
  4333. for apid in apertures:
  4334. for geo_el in apertures[apid]['geometry']:
  4335. solid_geometry.append(geo_el['solid'])
  4336. solid_geometry = MultiPolygon(solid_geometry)
  4337. solid_geometry = solid_geometry.buffer(0.0000001)
  4338. obj_init.solid_geometry = deepcopy(solid_geometry)
  4339. obj_init.apertures = deepcopy(apertures)
  4340. # clear the working objects (perhaps not necessary due of Python GC)
  4341. apertures.clear()
  4342. if not self.collection.get_selected():
  4343. log.warning("App.convert_any2gerber --> No object selected")
  4344. self.inform.emit('[WARNING_NOTCL] %s' %
  4345. _("No object is selected. Select an object and try again."))
  4346. return
  4347. for obj in self.collection.get_selected():
  4348. obj_name = obj.options["name"]
  4349. try:
  4350. if obj.kind == 'excellon':
  4351. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4352. elif obj.kind == 'geometry':
  4353. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4354. else:
  4355. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4356. except Exception as e:
  4357. return "Operation failed: %s" % str(e)
  4358. def convert_any2excellon(self):
  4359. """
  4360. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4361. :return:
  4362. """
  4363. def initialize_geometry(obj_init, app):
  4364. tools = {}
  4365. tooluid = 1
  4366. obj_init.solid_geometry = []
  4367. for geo in obj.solid_geometry:
  4368. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4369. continue
  4370. minx, miny, maxx, maxy = geo.bounds
  4371. new_dia = min([maxx-minx, maxy-miny])
  4372. new_drill = geo.centroid
  4373. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4374. current_tooldias = []
  4375. if tools:
  4376. for tool in tools:
  4377. if tools[tool] and 'tooldia' in tools[tool]:
  4378. current_tooldias.append(tools[tool]['tooldia'])
  4379. if new_dia in current_tooldias:
  4380. for tool in tools:
  4381. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4382. new_dia)):
  4383. tools[tool]['drills'].append(new_drill)
  4384. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4385. else:
  4386. tools[tooluid] = {}
  4387. tools[tooluid]['tooldia'] = new_dia
  4388. tools[tooluid]['drills'] = [new_drill]
  4389. tools[tooluid]['slots'] = []
  4390. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4391. tooluid += 1
  4392. try:
  4393. obj_init.solid_geometry.append(new_drill_geo)
  4394. except (TypeError, AttributeError):
  4395. obj_init.solid_geometry = [new_drill_geo]
  4396. obj_init.tools = deepcopy(tools)
  4397. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4398. def initialize_gerber(obj_init, app):
  4399. tools = {}
  4400. tooluid = 1
  4401. obj_init.solid_geometry = []
  4402. for apid in obj.apertures:
  4403. if 'geometry' in obj.apertures[apid]:
  4404. for geo_dict in obj.apertures[apid]['geometry']:
  4405. if 'follow' in geo_dict:
  4406. if isinstance(geo_dict['follow'], Point):
  4407. geo = geo_dict['solid']
  4408. minx, miny, maxx, maxy = geo.bounds
  4409. new_dia = min([maxx - minx, maxy - miny])
  4410. new_drill = geo.centroid
  4411. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4412. current_tooldias = []
  4413. if tools:
  4414. for tool in tools:
  4415. if tools[tool] and 'tooldia' in tools[tool]:
  4416. current_tooldias.append(
  4417. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4418. )
  4419. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4420. for tool in tools:
  4421. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4422. '%.*f' % (self.decimals, new_dia)):
  4423. if new_drill not in tools[tool]['drills']:
  4424. tools[tool]['drills'].append(new_drill)
  4425. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4426. else:
  4427. tools[tooluid] = {}
  4428. tools[tooluid]['tooldia'] = new_dia
  4429. tools[tooluid]['drills'] = [new_drill]
  4430. tools[tooluid]['slots'] = []
  4431. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4432. tooluid += 1
  4433. try:
  4434. obj_init.solid_geometry.append(new_drill_geo)
  4435. except (TypeError, AttributeError):
  4436. obj_init.solid_geometry = [new_drill_geo]
  4437. elif isinstance(geo_dict['follow'], LineString):
  4438. geo_coords = list(geo_dict['follow'].coords)
  4439. # slots can have only a start and stop point and no intermediate points
  4440. if len(geo_coords) != 2:
  4441. continue
  4442. geo = geo_dict['solid']
  4443. try:
  4444. new_dia = obj.apertures[apid]['size']
  4445. except Exception:
  4446. continue
  4447. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4448. new_slot_geo = geo
  4449. current_tooldias = []
  4450. if tools:
  4451. for tool in tools:
  4452. if tools[tool] and 'tooldia' in tools[tool]:
  4453. current_tooldias.append(
  4454. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4455. )
  4456. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4457. for tool in tools:
  4458. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4459. '%.*f' % (self.decimals, new_dia)):
  4460. if new_slot not in tools[tool]['slots']:
  4461. tools[tool]['slots'].append(new_slot)
  4462. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4463. else:
  4464. tools[tooluid] = {}
  4465. tools[tooluid]['tooldia'] = new_dia
  4466. tools[tooluid]['drills'] = []
  4467. tools[tooluid]['slots'] = [new_slot]
  4468. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4469. tooluid += 1
  4470. try:
  4471. obj_init.solid_geometry.append(new_slot_geo)
  4472. except (TypeError, AttributeError):
  4473. obj_init.solid_geometry = [new_slot_geo]
  4474. obj_init.tools = deepcopy(tools)
  4475. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4476. if not self.collection.get_selected():
  4477. log.warning("App.convert_any2excellon--> No object selected")
  4478. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4479. return
  4480. for obj in self.collection.get_selected():
  4481. obj_name = obj.options["name"]
  4482. try:
  4483. if obj.kind == 'gerber':
  4484. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4485. elif obj.kind == 'geometry':
  4486. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4487. else:
  4488. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4489. except Exception as e:
  4490. return "Operation failed: %s" % str(e)
  4491. def abort_all_tasks(self):
  4492. """
  4493. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4494. on the first possible occasion.
  4495. :return:
  4496. """
  4497. if self.abort_flag is False:
  4498. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4499. self.abort_flag = True
  4500. self.cleanup.emit()
  4501. def app_is_idle(self):
  4502. if self.abort_flag:
  4503. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4504. self.abort_flag = False
  4505. def on_selectall(self):
  4506. """
  4507. Will draw a selection box shape around the selected objects.
  4508. :return:
  4509. """
  4510. self.defaults.report_usage("on_selectall()")
  4511. # delete the possible selection box around a possible selected object
  4512. self.delete_selection_shape()
  4513. for name in self.collection.get_names():
  4514. self.collection.set_active(name)
  4515. curr_sel_obj = self.collection.get_by_name(name)
  4516. # create the selection box around the selected object
  4517. if self.defaults['global_selection_shape'] is True:
  4518. self.draw_selection_shape(curr_sel_obj)
  4519. def on_toggle_preferences(self):
  4520. pref_open = False
  4521. for idx in range(self.ui.plot_tab_area.count()):
  4522. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4523. pref_open = True
  4524. if pref_open:
  4525. for idx in range(self.ui.plot_tab_area.count()):
  4526. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4527. self.ui.plot_tab_area.removeTab(idx)
  4528. break
  4529. self.ui.pref_status_label.setStyleSheet("")
  4530. else:
  4531. self.on_preferences()
  4532. def on_preferences(self):
  4533. """
  4534. Adds the Preferences in a Tab in Plot Area
  4535. :return:
  4536. """
  4537. # add the tab if it was closed
  4538. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4539. # delete the absolute and relative position and messages in the infobar
  4540. # self.ui.position_label.setText("")
  4541. # self.ui.rel_position_label.setText("")
  4542. # hide coordinates toolbars in the infobar while in DB
  4543. self.ui.coords_toolbar.hide()
  4544. self.ui.delta_coords_toolbar.hide()
  4545. # Switch plot_area to preferences page
  4546. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4547. # self.ui.show()
  4548. self.ui.pref_status_label.setStyleSheet("""
  4549. QLabel
  4550. {
  4551. color: black;
  4552. background-color: lightseagreen;
  4553. }
  4554. """
  4555. )
  4556. # detect changes in the preferences
  4557. for idx in range(self.ui.pref_tab_area.count()):
  4558. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4559. try:
  4560. try:
  4561. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4562. except (TypeError, AttributeError):
  4563. pass
  4564. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4565. except AttributeError:
  4566. pass
  4567. try:
  4568. try:
  4569. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4570. except (TypeError, AttributeError):
  4571. pass
  4572. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4573. except AttributeError:
  4574. pass
  4575. try:
  4576. try:
  4577. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4578. except (TypeError, AttributeError):
  4579. pass
  4580. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4581. except AttributeError:
  4582. pass
  4583. try:
  4584. try:
  4585. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4586. except (TypeError, AttributeError):
  4587. pass
  4588. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4589. except AttributeError:
  4590. pass
  4591. try:
  4592. try:
  4593. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4594. except (TypeError, AttributeError):
  4595. pass
  4596. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4597. except AttributeError:
  4598. pass
  4599. def on_tools_database(self, source='app'):
  4600. """
  4601. Adds the Tools Database in a Tab in Plot Area.
  4602. :return:
  4603. """
  4604. for idx in range(self.ui.plot_tab_area.count()):
  4605. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4606. # there can be only one instance of Tools Database at one time
  4607. return
  4608. if source == 'app':
  4609. self.tools_db_tab = ToolsDB2(
  4610. app=self,
  4611. parent=self.ui,
  4612. callback_on_edited=self.on_tools_db_edited,
  4613. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4614. )
  4615. elif source == 'ncc':
  4616. self.tools_db_tab = ToolsDB2(
  4617. app=self,
  4618. parent=self.ui,
  4619. callback_on_edited=self.on_tools_db_edited,
  4620. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4621. )
  4622. elif source == 'paint':
  4623. self.tools_db_tab = ToolsDB2(
  4624. app=self,
  4625. parent=self.ui,
  4626. callback_on_edited=self.on_tools_db_edited,
  4627. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4628. )
  4629. elif source == 'iso':
  4630. self.tools_db_tab = ToolsDB2(
  4631. app=self,
  4632. parent=self.ui,
  4633. callback_on_edited=self.on_tools_db_edited,
  4634. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4635. )
  4636. # add the tab if it was closed
  4637. try:
  4638. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4639. self.tools_db_tab.setObjectName("database_tab")
  4640. except Exception as e:
  4641. log.debug("App.on_tools_database() --> %s" % str(e))
  4642. return
  4643. # delete the absolute and relative position and messages in the infobar
  4644. # self.ui.position_label.setText("")
  4645. # self.ui.rel_position_label.setText("")
  4646. # hide coordinates toolbars in the infobar while in DB
  4647. self.ui.coords_toolbar.hide()
  4648. self.ui.delta_coords_toolbar.hide()
  4649. # Switch plot_area to preferences page
  4650. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4651. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4652. self.tools_db_tab.ui_connect()
  4653. def on_tools_db_edited(self):
  4654. """
  4655. Executed whenever a tool is edited in Tools Database.
  4656. Will color the text of the Tools Database tab to Red color.
  4657. :return:
  4658. """
  4659. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4660. for idx in range(self.ui.plot_tab_area.count()):
  4661. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4662. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4663. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4664. self.tools_db_changed_flag = True
  4665. def on_geometry_tool_add_from_db_executed(self, tool):
  4666. """
  4667. Here add the tool from DB in the selected geometry object.
  4668. :return:
  4669. """
  4670. tool_from_db = deepcopy(tool)
  4671. obj = self.collection.get_active()
  4672. if obj.kind == 'geometry':
  4673. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4674. # close the tab and delete it
  4675. for idx in range(self.ui.plot_tab_area.count()):
  4676. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4677. wdg = self.ui.plot_tab_area.widget(idx)
  4678. wdg.deleteLater()
  4679. self.ui.plot_tab_area.removeTab(idx)
  4680. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4681. elif obj.kind == 'gerber':
  4682. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4683. # close the tab and delete it
  4684. for idx in range(self.ui.plot_tab_area.count()):
  4685. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4686. wdg = self.ui.plot_tab_area.widget(idx)
  4687. wdg.deleteLater()
  4688. self.ui.plot_tab_area.removeTab(idx)
  4689. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4690. else:
  4691. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4692. def on_plot_area_tab_closed(self, tab_obj_name):
  4693. """
  4694. Executed whenever a QTab is closed in the Plot Area.
  4695. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4696. :return:
  4697. """
  4698. if tab_obj_name == "preferences_tab":
  4699. self.preferencesUiManager.on_close_preferences_tab()
  4700. elif tab_obj_name == "database_tab":
  4701. # disconnect the signals from the table widget in tab
  4702. self.tools_db_tab.ui_disconnect()
  4703. if self.tools_db_changed_flag is True:
  4704. msgbox = QtWidgets.QMessageBox()
  4705. msgbox.setText(_("One or more Tools are edited.\n"
  4706. "Do you want to update the Tools Database?"))
  4707. msgbox.setWindowTitle(_("Save Tools Database"))
  4708. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4709. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4710. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4711. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4712. msgbox.setDefaultButton(bt_yes)
  4713. msgbox.exec_()
  4714. response = msgbox.clickedButton()
  4715. if response == bt_yes:
  4716. self.tools_db_tab.on_save_tools_db()
  4717. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4718. else:
  4719. self.tools_db_changed_flag = False
  4720. self.inform.emit('')
  4721. return
  4722. self.tools_db_tab.deleteLater()
  4723. elif tab_obj_name == "text_editor_tab":
  4724. self.toggle_codeeditor = False
  4725. elif tab_obj_name == "bookmarks_tab":
  4726. self.book_dialog_tab.rebuild_actions()
  4727. self.book_dialog_tab.deleteLater()
  4728. else:
  4729. pass
  4730. # restore the coords toolbars
  4731. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4732. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4733. def on_flipy(self):
  4734. """
  4735. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4736. :return:
  4737. """
  4738. self.defaults.report_usage("on_flipy()")
  4739. obj_list = self.collection.get_selected()
  4740. xminlist = []
  4741. yminlist = []
  4742. xmaxlist = []
  4743. ymaxlist = []
  4744. if not obj_list:
  4745. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4746. else:
  4747. try:
  4748. # first get a bounding box to fit all
  4749. for obj in obj_list:
  4750. xmin, ymin, xmax, ymax = obj.bounds()
  4751. xminlist.append(xmin)
  4752. yminlist.append(ymin)
  4753. xmaxlist.append(xmax)
  4754. ymaxlist.append(ymax)
  4755. # get the minimum x,y and maximum x,y for all objects selected
  4756. xminimal = min(xminlist)
  4757. yminimal = min(yminlist)
  4758. xmaximal = max(xmaxlist)
  4759. ymaximal = max(ymaxlist)
  4760. px = 0.5 * (xminimal + xmaximal)
  4761. py = 0.5 * (yminimal + ymaximal)
  4762. # execute mirroring
  4763. for obj in obj_list:
  4764. obj.mirror('X', [px, py])
  4765. obj.plot()
  4766. self.app_obj.object_changed.emit(obj)
  4767. self.inform.emit('[success] %s' %
  4768. _("Flip on Y axis done."))
  4769. except Exception as e:
  4770. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4771. return
  4772. def on_flipx(self):
  4773. """
  4774. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4775. :return:
  4776. """
  4777. self.defaults.report_usage("on_flipx()")
  4778. obj_list = self.collection.get_selected()
  4779. xminlist = []
  4780. yminlist = []
  4781. xmaxlist = []
  4782. ymaxlist = []
  4783. if not obj_list:
  4784. self.inform.emit('[WARNING_NOTCL] %s' %
  4785. _("No object selected to Flip on X axis."))
  4786. else:
  4787. try:
  4788. # first get a bounding box to fit all
  4789. for obj in obj_list:
  4790. xmin, ymin, xmax, ymax = obj.bounds()
  4791. xminlist.append(xmin)
  4792. yminlist.append(ymin)
  4793. xmaxlist.append(xmax)
  4794. ymaxlist.append(ymax)
  4795. # get the minimum x,y and maximum x,y for all objects selected
  4796. xminimal = min(xminlist)
  4797. yminimal = min(yminlist)
  4798. xmaximal = max(xmaxlist)
  4799. ymaximal = max(ymaxlist)
  4800. px = 0.5 * (xminimal + xmaximal)
  4801. py = 0.5 * (yminimal + ymaximal)
  4802. # execute mirroring
  4803. for obj in obj_list:
  4804. obj.mirror('Y', [px, py])
  4805. obj.plot()
  4806. self.app_obj.object_changed.emit(obj)
  4807. self.inform.emit('[success] %s' %
  4808. _("Flip on X axis done."))
  4809. except Exception as e:
  4810. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4811. return
  4812. def on_rotate(self, silent=False, preset=None):
  4813. """
  4814. Executed when Options -> Rotate Selection menu entry is clicked.
  4815. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4816. :param preset: A value to be used as predefined angle for rotation.
  4817. :return:
  4818. """
  4819. self.defaults.report_usage("on_rotate()")
  4820. obj_list = self.collection.get_selected()
  4821. xminlist = []
  4822. yminlist = []
  4823. xmaxlist = []
  4824. ymaxlist = []
  4825. if not obj_list:
  4826. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4827. else:
  4828. if silent is False:
  4829. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4830. min=-360, max=360, decimals=4,
  4831. init_val=float(self.defaults['tools_transform_rotate']))
  4832. num, ok = rotatebox.get_value()
  4833. else:
  4834. num = preset
  4835. ok = True
  4836. if ok:
  4837. try:
  4838. # first get a bounding box to fit all
  4839. for obj in obj_list:
  4840. xmin, ymin, xmax, ymax = obj.bounds()
  4841. xminlist.append(xmin)
  4842. yminlist.append(ymin)
  4843. xmaxlist.append(xmax)
  4844. ymaxlist.append(ymax)
  4845. # get the minimum x,y and maximum x,y for all objects selected
  4846. xminimal = min(xminlist)
  4847. yminimal = min(yminlist)
  4848. xmaximal = max(xmaxlist)
  4849. ymaximal = max(ymaxlist)
  4850. px = 0.5 * (xminimal + xmaximal)
  4851. py = 0.5 * (yminimal + ymaximal)
  4852. for sel_obj in obj_list:
  4853. sel_obj.rotate(-float(num), point=(px, py))
  4854. sel_obj.plot()
  4855. self.app_obj.object_changed.emit(sel_obj)
  4856. self.inform.emit('[success] %s' % _("Rotation done."))
  4857. except Exception as e:
  4858. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4859. return
  4860. def on_skewx(self):
  4861. """
  4862. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4863. :return:
  4864. """
  4865. self.defaults.report_usage("on_skewx()")
  4866. obj_list = self.collection.get_selected()
  4867. xminlist = []
  4868. yminlist = []
  4869. if not obj_list:
  4870. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4871. else:
  4872. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4873. min=-360, max=360, decimals=4,
  4874. init_val=float(self.defaults['tools_transform_skew_x']))
  4875. num, ok = skewxbox.get_value()
  4876. if ok:
  4877. # first get a bounding box to fit all
  4878. for obj in obj_list:
  4879. xmin, ymin, xmax, ymax = obj.bounds()
  4880. xminlist.append(xmin)
  4881. yminlist.append(ymin)
  4882. # get the minimum x,y and maximum x,y for all objects selected
  4883. xminimal = min(xminlist)
  4884. yminimal = min(yminlist)
  4885. for obj in obj_list:
  4886. obj.skew(num, 0, point=(xminimal, yminimal))
  4887. obj.plot()
  4888. self.app_obj.object_changed.emit(obj)
  4889. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4890. def on_skewy(self):
  4891. """
  4892. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4893. :return:
  4894. """
  4895. self.defaults.report_usage("on_skewy()")
  4896. obj_list = self.collection.get_selected()
  4897. xminlist = []
  4898. yminlist = []
  4899. if not obj_list:
  4900. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4901. else:
  4902. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4903. min=-360, max=360, decimals=4,
  4904. init_val=float(self.defaults['tools_transform_skew_y']))
  4905. num, ok = skewybox.get_value()
  4906. if ok:
  4907. # first get a bounding box to fit all
  4908. for obj in obj_list:
  4909. xmin, ymin, xmax, ymax = obj.bounds()
  4910. xminlist.append(xmin)
  4911. yminlist.append(ymin)
  4912. # get the minimum x,y and maximum x,y for all objects selected
  4913. xminimal = min(xminlist)
  4914. yminimal = min(yminlist)
  4915. for obj in obj_list:
  4916. obj.skew(0, num, point=(xminimal, yminimal))
  4917. obj.plot()
  4918. self.app_obj.object_changed.emit(obj)
  4919. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4920. def on_plots_updated(self):
  4921. """
  4922. Callback used to report when the plots have changed.
  4923. Adjust axes and zooms to fit.
  4924. :return: None
  4925. """
  4926. if self.is_legacy is False:
  4927. self.plotcanvas.update()
  4928. else:
  4929. self.plotcanvas.auto_adjust_axes()
  4930. self.on_zoom_fit()
  4931. self.collection.update_view()
  4932. # self.inform.emit(_("Plots updated ..."))
  4933. def on_toolbar_replot(self):
  4934. """
  4935. Callback for toolbar button. Re-plots all objects.
  4936. :return: None
  4937. """
  4938. self.log.debug("on_toolbar_replot()")
  4939. try:
  4940. obj = self.collection.get_active()
  4941. if obj:
  4942. obj.read_form()
  4943. else:
  4944. self.on_zoom_fit()
  4945. except AttributeError as e:
  4946. log.debug("on_toolbar_replot() -> %s" % str(e))
  4947. pass
  4948. self.plot_all()
  4949. def grid_status(self):
  4950. return True if self.ui.grid_snap_btn.isChecked() else False
  4951. def populate_cmenu_grids(self):
  4952. units = self.defaults['units'].lower()
  4953. # for act in self.ui.cmenu_gridmenu.actions():
  4954. # act.triggered.disconnect()
  4955. self.ui.cmenu_gridmenu.clear()
  4956. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4957. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4958. _("Grid On/Off"))
  4959. grid_toggle.setCheckable(True)
  4960. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4961. self.ui.cmenu_gridmenu.addSeparator()
  4962. for grid in sorted_list:
  4963. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4964. "%s" % str(grid))
  4965. action.triggered.connect(self.set_grid)
  4966. self.ui.cmenu_gridmenu.addSeparator()
  4967. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4968. _("Add"))
  4969. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4970. _("Delete"))
  4971. grid_add.triggered.connect(self.on_grid_add)
  4972. grid_delete.triggered.connect(self.on_grid_delete)
  4973. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4974. def set_grid(self):
  4975. menu_action = self.sender()
  4976. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4977. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4978. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4979. def on_grid_add(self):
  4980. # ## Current application units in lower Case
  4981. units = self.defaults['units'].lower()
  4982. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4983. text=_('Enter a Grid Value:'),
  4984. min=0.0000, max=99.9999, decimals=4)
  4985. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4986. val, ok = grid_add_popup.get_value()
  4987. if ok:
  4988. if float(val) == 0:
  4989. self.inform.emit('[WARNING_NOTCL] %s' %
  4990. _("Please enter a grid value with non-zero value, in Float format."))
  4991. return
  4992. else:
  4993. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4994. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4995. self.inform.emit('[success] %s...' % _("New Grid added"))
  4996. else:
  4997. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4998. else:
  4999. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5000. def on_grid_delete(self):
  5001. # ## Current application units in lower Case
  5002. units = self.defaults['units'].lower()
  5003. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5004. text='Enter a Grid Value:',
  5005. min=0.0000, max=99.9999, decimals=4)
  5006. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5007. val, ok = grid_del_popup.get_value()
  5008. if ok:
  5009. if float(val) == 0:
  5010. self.inform.emit('[WARNING_NOTCL] %s' %
  5011. _("Please enter a grid value with non-zero value, in Float format."))
  5012. return
  5013. else:
  5014. try:
  5015. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5016. except ValueError:
  5017. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5018. return
  5019. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5020. else:
  5021. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5022. def on_shortcut_list(self):
  5023. self.defaults.report_usage("on_shortcut_list()")
  5024. # add the tab if it was closed
  5025. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5026. # delete the absolute and relative position and messages in the infobar
  5027. # self.ui.position_label.setText("")
  5028. # self.ui.rel_position_label.setText("")
  5029. # hide coordinates toolbars in the infobar while in DB
  5030. self.ui.coords_toolbar.hide()
  5031. self.ui.delta_coords_toolbar.hide()
  5032. # Switch plot_area to preferences page
  5033. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5034. # self.ui.show()
  5035. def on_select_tab(self, name):
  5036. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5037. if self.ui.splitter.sizes()[0] == 0:
  5038. self.ui.splitter.setSizes([1, 1])
  5039. else:
  5040. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5041. self.ui.splitter.setSizes([0, 1])
  5042. if name == 'project':
  5043. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5044. elif name == 'selected':
  5045. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5046. elif name == 'tool':
  5047. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5048. def on_copy_name(self):
  5049. self.defaults.report_usage("on_copy_name()")
  5050. obj = self.collection.get_active()
  5051. try:
  5052. name = obj.options["name"]
  5053. except AttributeError:
  5054. log.debug("on_copy_name() --> No object selected to copy it's name")
  5055. self.inform.emit('[WARNING_NOTCL] %s' %
  5056. _(" No object selected to copy it's name"))
  5057. return
  5058. self.clipboard.setText(name)
  5059. self.inform.emit(_("Name copied on clipboard ..."))
  5060. def on_mouse_click_over_plot(self, event):
  5061. """
  5062. Default actions are:
  5063. :param event: Contains information about the event, like which button
  5064. was clicked, the pixel coordinates and the axes coordinates.
  5065. :return: None
  5066. """
  5067. self.pos = []
  5068. if self.is_legacy is False:
  5069. event_pos = event.pos
  5070. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5071. # # Set the mouse button for panning
  5072. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5073. else:
  5074. event_pos = (event.xdata, event.ydata)
  5075. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5076. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5077. # So it can receive key presses
  5078. self.plotcanvas.native.setFocus()
  5079. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5080. if self.grid_status():
  5081. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5082. else:
  5083. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5084. try:
  5085. if event.button == 1:
  5086. # Reset here the relative coordinates so there is a new reference on the click position
  5087. if self.rel_point1 is None:
  5088. self.rel_point1 = self.pos
  5089. else:
  5090. self.rel_point2 = copy(self.rel_point1)
  5091. self.rel_point1 = self.pos
  5092. self.on_mouse_move_over_plot(event, origin_click=True)
  5093. except Exception as e:
  5094. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5095. def on_mouse_double_click_over_plot(self, event):
  5096. if event.button == 1:
  5097. self.doubleclick = True
  5098. def on_mouse_move_over_plot(self, event, origin_click=None):
  5099. """
  5100. Callback for the mouse motion event over the plot.
  5101. :param event: Contains information about the event.
  5102. :param origin_click
  5103. :return: None
  5104. """
  5105. if self.is_legacy is False:
  5106. event_pos = event.pos
  5107. if self.defaults["global_pan_button"] == '2':
  5108. pan_button = 2
  5109. else:
  5110. pan_button = 3
  5111. self.event_is_dragging = event.is_dragging
  5112. else:
  5113. event_pos = (event.xdata, event.ydata)
  5114. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5115. if self.defaults["global_pan_button"] == '2':
  5116. pan_button = 3
  5117. else:
  5118. pan_button = 2
  5119. self.event_is_dragging = self.plotcanvas.is_dragging
  5120. # So it can receive key presses but not when the Tcl Shell is active
  5121. if not self.ui.shell_dock.isVisible():
  5122. if not self.plotcanvas.native.hasFocus():
  5123. self.plotcanvas.native.setFocus()
  5124. self.pos_jump = event_pos
  5125. self.ui.popMenu.mouse_is_panning = False
  5126. if origin_click is None:
  5127. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5128. if event.button == pan_button and self.event_is_dragging == 1:
  5129. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5130. if self.ui.popMenu.popup_active:
  5131. self.ui.popMenu.popup_active = False
  5132. return
  5133. self.ui.popMenu.mouse_is_panning = True
  5134. return
  5135. if self.rel_point1 is not None:
  5136. try: # May fail in case mouse not within axes
  5137. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5138. if pos_canvas[0] is None or pos_canvas[1] is None:
  5139. return
  5140. if self.grid_status():
  5141. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5142. # Update cursor
  5143. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5144. symbol='++', edge_color=self.cursor_color_3D,
  5145. edge_width=self.defaults["global_cursor_width"],
  5146. size=self.defaults["global_cursor_size"])
  5147. else:
  5148. pos = (pos_canvas[0], pos_canvas[1])
  5149. self.dx = pos[0] - float(self.rel_point1[0])
  5150. self.dy = pos[1] - float(self.rel_point1[1])
  5151. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5152. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5153. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5154. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5155. units = self.defaults["units"].lower()
  5156. self.plotcanvas.text_hud.text = \
  5157. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5158. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5159. self.mouse = [pos[0], pos[1]]
  5160. if self.defaults['global_selection_shape'] is False:
  5161. self.selection_type = None
  5162. return
  5163. # if the mouse is moved and the LMB is clicked then the action is a selection
  5164. if self.event_is_dragging == 1 and event.button == 1:
  5165. self.delete_selection_shape()
  5166. if self.dx < 0:
  5167. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5168. face_color=self.defaults['global_alt_sel_fill'])
  5169. self.selection_type = False
  5170. elif self.dx >= 0:
  5171. self.draw_moving_selection_shape(self.pos, pos)
  5172. self.selection_type = True
  5173. else:
  5174. self.selection_type = None
  5175. else:
  5176. self.selection_type = None
  5177. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5178. if self.defaults['global_hover']:
  5179. for obj in self.collection.get_list():
  5180. try:
  5181. # select the object(s) only if it is enabled (plotted)
  5182. if obj.options['plot']:
  5183. if obj not in self.collection.get_selected():
  5184. poly_obj = Polygon(
  5185. [(obj.options['xmin'], obj.options['ymin']),
  5186. (obj.options['xmax'], obj.options['ymin']),
  5187. (obj.options['xmax'], obj.options['ymax']),
  5188. (obj.options['xmin'], obj.options['ymax'])]
  5189. )
  5190. if Point(pos).within(poly_obj):
  5191. if obj.isHovering is False:
  5192. obj.isHovering = True
  5193. obj.notHovering = True
  5194. # create the selection box around the selected object
  5195. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5196. else:
  5197. if obj.notHovering is True:
  5198. obj.notHovering = False
  5199. obj.isHovering = False
  5200. self.delete_hover_shape()
  5201. except Exception:
  5202. # the Exception here will happen if we try to select on screen and we have an
  5203. # newly (and empty) just created Geometry or Excellon object that do not have the
  5204. # xmin, xmax, ymin, ymax options.
  5205. # In this case poly_obj creation (see above) will fail
  5206. pass
  5207. except Exception as e:
  5208. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5209. self.ui.position_label.setText("")
  5210. self.ui.rel_position_label.setText("")
  5211. self.mouse = None
  5212. def on_mouse_click_release_over_plot(self, event):
  5213. """
  5214. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5215. and has been registered in ''self.__init__()''.
  5216. :param event: contains information about the event.
  5217. :return:
  5218. """
  5219. if self.is_legacy is False:
  5220. event_pos = event.pos
  5221. right_button = 2
  5222. else:
  5223. event_pos = (event.xdata, event.ydata)
  5224. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5225. right_button = 3
  5226. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5227. if self.grid_status():
  5228. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5229. else:
  5230. pos = (pos_canvas[0], pos_canvas[1])
  5231. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5232. # canvas menu
  5233. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5234. self.ui.popMenu.mouse_is_panning = False
  5235. self.cursor = QtGui.QCursor()
  5236. self.populate_cmenu_grids()
  5237. self.ui.popMenu.popup(self.cursor.pos())
  5238. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5239. # selection and then select a type of selection ("enclosing" or "touching")
  5240. if event.button == 1: # left click
  5241. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5242. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5243. if modifiers == QtCore.Qt.ShiftModifier:
  5244. # do not auto open the Project Tab
  5245. self.click_noproject = True
  5246. self.clipboard.setText(
  5247. self.defaults["global_point_clipboard_format"] %
  5248. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5249. )
  5250. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5251. return
  5252. if self.doubleclick is True:
  5253. self.doubleclick = False
  5254. if self.collection.get_selected():
  5255. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5256. if self.ui.splitter.sizes()[0] == 0:
  5257. self.ui.splitter.setSizes([1, 1])
  5258. try:
  5259. # delete the selection shape(S) as it may be in the way
  5260. self.delete_selection_shape()
  5261. self.delete_hover_shape()
  5262. except Exception as e:
  5263. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5264. return
  5265. else:
  5266. # WORKAROUND for LEGACY MODE
  5267. if self.is_legacy is True:
  5268. # if there is no move on canvas then we have no dragging selection
  5269. if self.dx == 0 or self.dy == 0:
  5270. self.selection_type = None
  5271. if self.selection_type is not None:
  5272. try:
  5273. self.selection_area_handler(self.pos, pos, self.selection_type)
  5274. self.selection_type = None
  5275. except Exception as e:
  5276. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5277. return
  5278. else:
  5279. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5280. if key_modifier == QtCore.Qt.ShiftModifier:
  5281. mod_key = 'Shift'
  5282. elif key_modifier == QtCore.Qt.ControlModifier:
  5283. mod_key = 'Control'
  5284. else:
  5285. mod_key = None
  5286. try:
  5287. if self.command_active is None:
  5288. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5289. # deselect, and if it's not selected then it will be selected
  5290. # If there is no active command (self.command_active is None) then we check if we clicked
  5291. # on a object by checking the bounding limits against mouse click position
  5292. if mod_key == self.defaults["global_mselect_key"]:
  5293. self.select_objects(key='multisel')
  5294. else:
  5295. # If there is no active command (self.command_active is None) then we check if
  5296. # we clicked on a object by checking the bounding limits against mouse click position
  5297. self.select_objects()
  5298. self.delete_hover_shape()
  5299. except Exception as e:
  5300. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5301. return
  5302. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5303. """
  5304. :param start_pos: mouse position when the selection LMB click was done
  5305. :param end_pos: mouse position when the left mouse button is released
  5306. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5307. :return:
  5308. """
  5309. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5310. # delete previous selection shape
  5311. self.delete_selection_shape()
  5312. # make all objects inactive
  5313. self.collection.set_all_inactive()
  5314. for obj in self.collection.get_list():
  5315. try:
  5316. # select the object(s) only if it is enabled (plotted)
  5317. if obj.options['plot']:
  5318. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5319. (obj.options['xmax'], obj.options['ymin']),
  5320. (obj.options['xmax'], obj.options['ymax']),
  5321. (obj.options['xmin'], obj.options['ymax'])])
  5322. if sel_type is True:
  5323. if poly_obj.within(poly_selection):
  5324. # create the selection box around the selected object
  5325. if self.defaults['global_selection_shape'] is True:
  5326. self.draw_selection_shape(obj)
  5327. self.collection.set_active(obj.options['name'])
  5328. else:
  5329. if poly_selection.intersects(poly_obj):
  5330. # create the selection box around the selected object
  5331. if self.defaults['global_selection_shape'] is True:
  5332. self.draw_selection_shape(obj)
  5333. self.collection.set_active(obj.options['name'])
  5334. obj.selection_shape_drawn = True
  5335. except Exception as e:
  5336. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5337. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5338. # In this case poly_obj creation (see above) will fail
  5339. log.debug("App.selection_area_handler() --> %s" % str(e))
  5340. def select_objects(self, key=None):
  5341. """
  5342. Will select objects clicked on canvas
  5343. :param key: for future use in cumulative selection
  5344. :return:
  5345. """
  5346. # list where we store the overlapped objects under our mouse left click position
  5347. if key is None:
  5348. self.objects_under_the_click_list = []
  5349. # Populate the list with the overlapped objects on the click position
  5350. curr_x, curr_y = self.pos
  5351. for obj in self.all_objects_list:
  5352. # ScriptObject and DocumentObject objects can't be selected
  5353. if obj.kind == 'script' or obj.kind == 'document':
  5354. continue
  5355. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5356. continue
  5357. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5358. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5359. if obj.options['name'] not in self.objects_under_the_click_list:
  5360. if obj.options['plot']:
  5361. # add objects to the objects_under_the_click list only if the object is plotted
  5362. # (active and not disabled)
  5363. self.objects_under_the_click_list.append(obj.options['name'])
  5364. try:
  5365. if self.objects_under_the_click_list:
  5366. curr_sel_obj = self.collection.get_active()
  5367. # case when there is only an object under the click and we toggle it
  5368. if len(self.objects_under_the_click_list) == 1:
  5369. if curr_sel_obj is None:
  5370. self.collection.set_active(self.objects_under_the_click_list[0])
  5371. curr_sel_obj = self.collection.get_active()
  5372. # create the selection box around the selected object
  5373. if self.defaults['global_selection_shape'] is True:
  5374. self.draw_selection_shape(curr_sel_obj)
  5375. curr_sel_obj.selection_shape_drawn = True
  5376. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5377. self.collection.on_objects_selection(False)
  5378. self.delete_selection_shape()
  5379. curr_sel_obj.selection_shape_drawn = False
  5380. self.collection.set_active(self.objects_under_the_click_list[0])
  5381. curr_sel_obj = self.collection.get_active()
  5382. # create the selection box around the selected object
  5383. if self.defaults['global_selection_shape'] is True:
  5384. self.draw_selection_shape(curr_sel_obj)
  5385. curr_sel_obj.selection_shape_drawn = True
  5386. self.selected_message(curr_sel_obj=curr_sel_obj)
  5387. elif curr_sel_obj.selection_shape_drawn is False:
  5388. if self.defaults['global_selection_shape'] is True:
  5389. self.draw_selection_shape(curr_sel_obj)
  5390. curr_sel_obj.selection_shape_drawn = True
  5391. else:
  5392. self.collection.on_objects_selection(False)
  5393. self.delete_selection_shape()
  5394. if self.call_source != 'app':
  5395. self.call_source = 'app'
  5396. self.selected_message(curr_sel_obj=curr_sel_obj)
  5397. else:
  5398. # If there is no selected object
  5399. # make active the first element of the overlapped objects list
  5400. if self.collection.get_active() is None:
  5401. self.collection.set_active(self.objects_under_the_click_list[0])
  5402. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5403. name_sel_obj = self.collection.get_active().options['name']
  5404. # In case that there is a selected object but it is not in the overlapped object list
  5405. # make that object inactive and activate the first element in the overlapped object list
  5406. if name_sel_obj not in self.objects_under_the_click_list:
  5407. self.collection.set_inactive(name_sel_obj)
  5408. name_sel_obj = self.objects_under_the_click_list[0]
  5409. self.collection.set_active(name_sel_obj)
  5410. else:
  5411. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5412. self.collection.set_all_inactive()
  5413. self.collection.set_active(
  5414. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5415. curr_sel_obj = self.collection.get_active()
  5416. # delete the possible selection box around a possible selected object
  5417. self.delete_selection_shape()
  5418. curr_sel_obj.selection_shape_drawn = False
  5419. # create the selection box around the selected object
  5420. if self.defaults['global_selection_shape'] is True:
  5421. self.draw_selection_shape(curr_sel_obj)
  5422. curr_sel_obj.selection_shape_drawn = True
  5423. self.selected_message(curr_sel_obj=curr_sel_obj)
  5424. else:
  5425. # deselect everything
  5426. self.collection.on_objects_selection(False)
  5427. # delete the possible selection box around a possible selected object
  5428. self.delete_selection_shape()
  5429. for o in self.collection.get_list():
  5430. o.selection_shape_drawn = False
  5431. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5432. # only when working on App
  5433. if self.call_source == 'app':
  5434. if self.click_noproject is False:
  5435. # if the Tool Tab is in focus don't change focus to Project Tab
  5436. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5437. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5438. else:
  5439. # restore auto open the Project Tab
  5440. self.click_noproject = False
  5441. # delete any text in the status bar, implicitly the last object name that was selected
  5442. # self.inform.emit("")
  5443. else:
  5444. self.call_source = 'app'
  5445. except Exception as e:
  5446. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5447. def selected_message(self, curr_sel_obj):
  5448. if curr_sel_obj:
  5449. if curr_sel_obj.kind == 'gerber':
  5450. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5451. color='green',
  5452. name=str(curr_sel_obj.options['name']),
  5453. tx=_("selected"))
  5454. )
  5455. elif curr_sel_obj.kind == 'excellon':
  5456. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5457. color='brown',
  5458. name=str(curr_sel_obj.options['name']),
  5459. tx=_("selected"))
  5460. )
  5461. elif curr_sel_obj.kind == 'cncjob':
  5462. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5463. color='blue',
  5464. name=str(curr_sel_obj.options['name']),
  5465. tx=_("selected"))
  5466. )
  5467. elif curr_sel_obj.kind == 'geometry':
  5468. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5469. color='red',
  5470. name=str(curr_sel_obj.options['name']),
  5471. tx=_("selected"))
  5472. )
  5473. def delete_hover_shape(self):
  5474. self.hover_shapes.clear()
  5475. self.hover_shapes.redraw()
  5476. def draw_hover_shape(self, sel_obj, color=None):
  5477. """
  5478. :param sel_obj: The object for which the hover shape must be drawn
  5479. :param color: The color of the hover shape
  5480. :return: None
  5481. """
  5482. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5483. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5484. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5485. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5486. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5487. if self.defaults['units'].upper() == 'MM':
  5488. hover_rect = hover_rect.buffer(-0.1)
  5489. hover_rect = hover_rect.buffer(0.2)
  5490. else:
  5491. hover_rect = hover_rect.buffer(-0.00393)
  5492. hover_rect = hover_rect.buffer(0.00787)
  5493. # if color:
  5494. # face = Color(color)
  5495. # face.alpha = 0.2
  5496. # outline = Color(color, alpha=0.8)
  5497. # else:
  5498. # face = Color(self.defaults['global_sel_fill'])
  5499. # face.alpha = 0.2
  5500. # outline = self.defaults['global_sel_line']
  5501. if color:
  5502. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5503. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5504. else:
  5505. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5506. outline = self.defaults['global_sel_line']
  5507. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5508. if self.is_legacy is True:
  5509. self.hover_shapes.redraw()
  5510. def delete_selection_shape(self):
  5511. self.move_tool.sel_shapes.clear()
  5512. self.move_tool.sel_shapes.redraw()
  5513. def draw_selection_shape(self, sel_obj, color=None):
  5514. """
  5515. Will draw a selection shape around the selected object.
  5516. :param sel_obj: The object for which the selection shape must be drawn
  5517. :param color: The color for the selection shape.
  5518. :return: None
  5519. """
  5520. if sel_obj is None:
  5521. return
  5522. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5523. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5524. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5525. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5526. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5527. if self.defaults['units'].upper() == 'MM':
  5528. sel_rect = sel_rect.buffer(-0.1)
  5529. sel_rect = sel_rect.buffer(0.2)
  5530. else:
  5531. sel_rect = sel_rect.buffer(-0.00393)
  5532. sel_rect = sel_rect.buffer(0.00787)
  5533. if color:
  5534. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5535. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5536. else:
  5537. if self.is_legacy is False:
  5538. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5539. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5540. else:
  5541. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5542. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5543. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5544. color=outline,
  5545. face_color=face,
  5546. update=True,
  5547. layer=0,
  5548. tolerance=None))
  5549. if self.is_legacy is True:
  5550. self.move_tool.sel_shapes.redraw()
  5551. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5552. """
  5553. Will draw a selection shape when dragging mouse on canvas.
  5554. :param old_coords: Old coordinates
  5555. :param coords: New coordinates
  5556. :param kwargs: Keyword arguments
  5557. :return:
  5558. """
  5559. if 'color' in kwargs:
  5560. color = kwargs['color']
  5561. else:
  5562. color = self.defaults['global_sel_line']
  5563. if 'face_color' in kwargs:
  5564. face_color = kwargs['face_color']
  5565. else:
  5566. face_color = self.defaults['global_sel_fill']
  5567. if 'face_alpha' in kwargs:
  5568. face_alpha = kwargs['face_alpha']
  5569. else:
  5570. face_alpha = 0.3
  5571. x0, y0 = old_coords
  5572. x1, y1 = coords
  5573. pt1 = (x0, y0)
  5574. pt2 = (x1, y0)
  5575. pt3 = (x1, y1)
  5576. pt4 = (x0, y1)
  5577. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5578. # color_t = Color(face_color)
  5579. # color_t.alpha = face_alpha
  5580. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5581. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5582. layer=0, tolerance=None)
  5583. if self.is_legacy is True:
  5584. self.move_tool.sel_shapes.redraw()
  5585. def on_file_new_click(self):
  5586. """
  5587. Callback for menu item File -> New.
  5588. Executed on clicking the Menu -> File -> New Project
  5589. :return:
  5590. """
  5591. if self.collection.get_list() and self.should_we_save:
  5592. msgbox = QtWidgets.QMessageBox()
  5593. # msgbox.setText("<B>Save changes ...</B>")
  5594. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5595. "Creating a New project will delete them.\n"
  5596. "Do you want to Save the project?"))
  5597. msgbox.setWindowTitle(_("Save changes"))
  5598. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5599. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5600. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5601. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5602. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5603. msgbox.setDefaultButton(bt_yes)
  5604. msgbox.exec_()
  5605. response = msgbox.clickedButton()
  5606. if response == bt_yes:
  5607. self.on_file_saveprojectas()
  5608. elif response == bt_cancel:
  5609. return
  5610. elif response == bt_no:
  5611. self.on_file_new()
  5612. else:
  5613. self.on_file_new()
  5614. self.inform.emit('[success] %s...' % _("New Project created"))
  5615. def on_file_new(self, cli=None):
  5616. """
  5617. Returns the application to its startup state. This method is thread-safe.
  5618. :param cli: Boolean. If True this method was run from command line
  5619. :return: None
  5620. """
  5621. self.defaults.report_usage("on_file_new")
  5622. # Remove everything from memory
  5623. App.log.debug("on_file_new()")
  5624. # close any editor that might be open
  5625. if self.call_source != 'app':
  5626. self.editor2object(cleanup=True)
  5627. # ## EDITOR section
  5628. self.geo_editor = AppGeoEditor(self)
  5629. self.exc_editor = AppExcEditor(self)
  5630. self.grb_editor = AppGerberEditor(self)
  5631. # Clear pool
  5632. self.clear_pool()
  5633. for obj in self.collection.get_list():
  5634. # delete shapes left drawn from mark shape_collections, if any
  5635. if isinstance(obj, GerberObject):
  5636. try:
  5637. obj.mark_shapes_storage.clear()
  5638. obj.mark_shapes.clear(update=True)
  5639. obj.mark_shapes.enabled = False
  5640. except AttributeError:
  5641. pass
  5642. # also delete annotation shapes, if any
  5643. elif isinstance(obj, CNCJobObject):
  5644. try:
  5645. obj.text_col.enabled = False
  5646. del obj.text_col
  5647. obj.annotation.clear(update=True)
  5648. del obj.annotation
  5649. except AttributeError:
  5650. pass
  5651. # delete the exclusion areas
  5652. self.exc_areas.clear_shapes()
  5653. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5654. self.shell.init_tcl()
  5655. # delete any selection shape on canvas
  5656. self.delete_selection_shape()
  5657. # delete all FlatCAM objects
  5658. self.collection.delete_all()
  5659. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5660. self.setup_component_editor()
  5661. # Clear project filename
  5662. self.project_filename = None
  5663. # Load the application defaults
  5664. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5665. # Re-fresh project options
  5666. self.on_options_app2project()
  5667. # Init FlatCAMTools
  5668. self.init_tools()
  5669. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5670. if cli is None:
  5671. # we need to go in reverse because once we remove a tab then the index changes
  5672. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5673. # and so on. Therefore the deletion should be done in reverse
  5674. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5675. for index in range(wdg_count, -1, -1):
  5676. try:
  5677. self.ui.plot_tab_area.closeTab(index)
  5678. except Exception as e:
  5679. log.debug("App.on_file_new() --> %s" % str(e))
  5680. # # And then add again the Plot Area
  5681. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5682. self.ui.plot_tab_area.protectTab(0)
  5683. # take the focus of the Notebook on Project Tab.
  5684. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5685. self.set_ui_title(name=_("New Project - Not saved"))
  5686. def obj_properties(self):
  5687. """
  5688. Will launch the object Properties Tool
  5689. :return:
  5690. """
  5691. self.defaults.report_usage("obj_properties()")
  5692. self.properties_tool.run(toggle=False)
  5693. def on_project_context_save(self):
  5694. """
  5695. Wrapper, will save the object function of it's type
  5696. :return:
  5697. """
  5698. sel_objects = self.collection.get_selected()
  5699. len_objects = len(sel_objects)
  5700. cnt = 0
  5701. if len_objects > 1:
  5702. for o in sel_objects:
  5703. if o.kind == 'cncjob':
  5704. cnt += 1
  5705. if len_objects == cnt:
  5706. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5707. _filter_ = self.defaults['cncjob_save_filters'] + \
  5708. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5709. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5710. try:
  5711. filename, _f = FCFileSaveDialog.get_saved_filename(
  5712. caption=_("Export Code ..."),
  5713. directory=dir_file_to_save,
  5714. ext_filter=_filter_
  5715. )
  5716. except TypeError:
  5717. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5718. ext_filter=_filter_)
  5719. filename = filename.rpartition('/')[0]
  5720. for ob in sel_objects:
  5721. ob.read_form()
  5722. fname = '%s/%s' % (filename, ob.options['name'])
  5723. ob.export_gcode_handler(fname, is_gcode=True)
  5724. return
  5725. obj = self.collection.get_active()
  5726. if type(obj) == GeometryObject:
  5727. self.on_file_exportdxf()
  5728. elif type(obj) == ExcellonObject:
  5729. self.on_file_saveexcellon()
  5730. elif type(obj) == CNCJobObject:
  5731. obj.on_exportgcode_button_click()
  5732. elif type(obj) == GerberObject:
  5733. self.on_file_savegerber()
  5734. elif type(obj) == ScriptObject:
  5735. self.on_file_savescript()
  5736. elif type(obj) == DocumentObject:
  5737. self.on_file_savedocument()
  5738. def obj_move(self):
  5739. """
  5740. Callback for the Move menu entry in various Context Menu's.
  5741. :return:
  5742. """
  5743. self.defaults.report_usage("obj_move()")
  5744. self.move_tool.run(toggle=False)
  5745. def on_fileopengerber(self, signal, name=None):
  5746. """
  5747. File menu callback for opening a Gerber.
  5748. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5749. :param name:
  5750. :return: None
  5751. """
  5752. self.defaults.report_usage("on_fileopengerber")
  5753. App.log.debug("on_fileopengerber()")
  5754. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5755. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5756. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5757. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5758. "*.outline);;" \
  5759. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5760. "*.mil);;" \
  5761. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5762. "Allegro Files (*.art);;" \
  5763. "Mentor Files (*.pho *.gdo);;" \
  5764. "All Files (*.*)"
  5765. if name is None:
  5766. try:
  5767. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5768. directory=self.get_last_folder(),
  5769. filter=_filter_,
  5770. initialFilter=self.last_op_gerber_filter)
  5771. except TypeError:
  5772. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5773. filenames = [str(filename) for filename in filenames]
  5774. self.last_op_gerber_filter = _f
  5775. else:
  5776. filenames = [name]
  5777. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5778. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5779. _("Opening Gerber file.")),
  5780. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5781. color=QtGui.QColor("gray"))
  5782. if len(filenames) == 0:
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5784. else:
  5785. for filename in filenames:
  5786. if filename != '':
  5787. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5788. def on_fileopenexcellon(self, signal, name=None):
  5789. """
  5790. File menu callback for opening an Excellon file.
  5791. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5792. :param name:
  5793. :return: None
  5794. """
  5795. self.defaults.report_usage("on_fileopenexcellon")
  5796. App.log.debug("on_fileopenexcellon()")
  5797. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5798. "All Files (*.*)"
  5799. if name is None:
  5800. try:
  5801. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5802. directory=self.get_last_folder(),
  5803. filter=_filter_,
  5804. initialFilter=self.last_op_excellon_filter)
  5805. except TypeError:
  5806. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5807. filenames = [str(filename) for filename in filenames]
  5808. self.last_op_excellon_filter = _f
  5809. else:
  5810. filenames = [str(name)]
  5811. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5812. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5813. _("Opening Excellon file.")),
  5814. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5815. color=QtGui.QColor("gray"))
  5816. if len(filenames) == 0:
  5817. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5818. else:
  5819. for filename in filenames:
  5820. if filename != '':
  5821. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5822. def on_fileopengcode(self, signal, name=None):
  5823. """
  5824. File menu call back for opening gcode.
  5825. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5826. :param name:
  5827. :return:
  5828. """
  5829. self.defaults.report_usage("on_fileopengcode")
  5830. App.log.debug("on_fileopengcode()")
  5831. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5832. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5833. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5834. "All Files (*.*)"
  5835. if name is None:
  5836. try:
  5837. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5838. directory=self.get_last_folder(),
  5839. filter=_filter_,
  5840. initialFilter=self.last_op_gcode_filter)
  5841. except TypeError:
  5842. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5843. filenames = [str(filename) for filename in filenames]
  5844. self.last_op_gcode_filter = _f
  5845. else:
  5846. filenames = [name]
  5847. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5848. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5849. _("Opening G-Code file.")),
  5850. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5851. color=QtGui.QColor("gray"))
  5852. if len(filenames) == 0:
  5853. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5854. else:
  5855. for filename in filenames:
  5856. if filename != '':
  5857. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5858. def on_file_openproject(self, signal):
  5859. """
  5860. File menu callback for opening a project.
  5861. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5862. :return: None
  5863. """
  5864. self.defaults.report_usage("on_file_openproject")
  5865. App.log.debug("on_file_openproject()")
  5866. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5867. try:
  5868. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5869. directory=self.get_last_folder(), filter=_filter_)
  5870. except TypeError:
  5871. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5872. # The Qt methods above will return a QString which can cause problems later.
  5873. # So far json.dump() will fail to serialize it.
  5874. # TODO: Improve the serialization methods and remove this fix.
  5875. filename = str(filename)
  5876. if filename == "":
  5877. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5878. else:
  5879. # self.worker_task.emit({'fcn': self.open_project,
  5880. # 'params': [filename]})
  5881. # The above was failing because open_project() is not
  5882. # thread safe. The new_project()
  5883. self.open_project(filename)
  5884. def on_fileopenhpgl2(self, signal, name=None):
  5885. """
  5886. File menu callback for opening a HPGL2.
  5887. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5888. :param name:
  5889. :return: None
  5890. """
  5891. self.defaults.report_usage("on_fileopenhpgl2")
  5892. App.log.debug("on_fileopenhpgl2()")
  5893. _filter_ = "HPGL2 Files (*.plt);;" \
  5894. "All Files (*.*)"
  5895. if name is None:
  5896. try:
  5897. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5898. directory=self.get_last_folder(),
  5899. filter=_filter_)
  5900. except TypeError:
  5901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5902. filenames = [str(filename) for filename in filenames]
  5903. else:
  5904. filenames = [name]
  5905. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5906. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5907. _("Opening HPGL2 file.")),
  5908. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5909. color=QtGui.QColor("gray"))
  5910. if len(filenames) == 0:
  5911. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5912. else:
  5913. for filename in filenames:
  5914. if filename != '':
  5915. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5916. def on_file_openconfig(self, signal):
  5917. """
  5918. File menu callback for opening a config file.
  5919. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5920. :return: None
  5921. """
  5922. self.defaults.report_usage("on_file_openconfig")
  5923. App.log.debug("on_file_openconfig()")
  5924. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5925. try:
  5926. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5927. directory=self.data_path, filter=_filter_)
  5928. except TypeError:
  5929. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5930. filter=_filter_)
  5931. if filename == "":
  5932. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5933. else:
  5934. self.open_config_file(filename)
  5935. def on_file_exportsvg(self):
  5936. """
  5937. Callback for menu item File->Export SVG.
  5938. :return: None
  5939. """
  5940. self.defaults.report_usage("on_file_exportsvg")
  5941. App.log.debug("on_file_exportsvg()")
  5942. obj = self.collection.get_active()
  5943. if obj is None:
  5944. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5945. msg = _("Please Select a Geometry object to export")
  5946. msgbox = QtWidgets.QMessageBox()
  5947. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5948. msgbox.setInformativeText(msg)
  5949. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5950. msgbox.setDefaultButton(bt_ok)
  5951. msgbox.exec_()
  5952. return
  5953. # Check for more compatible types and add as required
  5954. if (not isinstance(obj, GeometryObject)
  5955. and not isinstance(obj, GerberObject)
  5956. and not isinstance(obj, CNCJobObject)
  5957. and not isinstance(obj, ExcellonObject)):
  5958. msg = '[ERROR_NOTCL] %s' % \
  5959. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5960. msgbox = QtWidgets.QMessageBox()
  5961. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5962. msgbox.setInformativeText(msg)
  5963. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5964. msgbox.setDefaultButton(bt_ok)
  5965. msgbox.exec_()
  5966. return
  5967. name = obj.options["name"]
  5968. _filter = "SVG File (*.svg);;All Files (*.*)"
  5969. try:
  5970. filename, _f = FCFileSaveDialog.get_saved_filename(
  5971. caption=_("Export SVG"),
  5972. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5973. ext_filter=_filter)
  5974. except TypeError:
  5975. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5976. filename = str(filename)
  5977. if filename == "":
  5978. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5979. return
  5980. else:
  5981. self.export_svg(name, filename)
  5982. if self.defaults["global_open_style"] is False:
  5983. self.file_opened.emit("SVG", filename)
  5984. self.file_saved.emit("SVG", filename)
  5985. def on_file_exportpng(self):
  5986. self.defaults.report_usage("on_file_exportpng")
  5987. App.log.debug("on_file_exportpng()")
  5988. self.date = str(datetime.today()).rpartition('.')[0]
  5989. self.date = ''.join(c for c in self.date if c not in ':-')
  5990. self.date = self.date.replace(' ', '_')
  5991. data = None
  5992. if self.is_legacy is False:
  5993. image = _screenshot(alpha=False)
  5994. data = np.asarray(image)
  5995. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5996. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5997. return
  5998. filter_ = "PNG File (*.png);;All Files (*.*)"
  5999. try:
  6000. filename, _f = FCFileSaveDialog.get_saved_filename(
  6001. caption=_("Export PNG Image"),
  6002. directory=self.get_last_save_folder() + '/png_' + self.date,
  6003. ext_filter=filter_)
  6004. except TypeError:
  6005. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6006. filename = str(filename)
  6007. if filename == "":
  6008. self.inform.emit(_("Cancelled."))
  6009. return
  6010. else:
  6011. if self.is_legacy is False:
  6012. write_png(filename, data)
  6013. else:
  6014. self.plotcanvas.figure.savefig(filename)
  6015. if self.defaults["global_open_style"] is False:
  6016. self.file_opened.emit("png", filename)
  6017. self.file_saved.emit("png", filename)
  6018. def on_file_savegerber(self):
  6019. """
  6020. Callback for menu item in Project context menu.
  6021. :return: None
  6022. """
  6023. self.defaults.report_usage("on_file_savegerber")
  6024. App.log.debug("on_file_savegerber()")
  6025. obj = self.collection.get_active()
  6026. if obj is None:
  6027. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6028. return
  6029. # Check for more compatible types and add as required
  6030. if not isinstance(obj, GerberObject):
  6031. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6032. return
  6033. name = self.collection.get_active().options["name"]
  6034. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6035. try:
  6036. filename, _f = FCFileSaveDialog.get_saved_filename(
  6037. caption="Save Gerber source file",
  6038. directory=self.get_last_save_folder() + '/' + name,
  6039. ext_filter=_filter)
  6040. except TypeError:
  6041. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6042. filename = str(filename)
  6043. if filename == "":
  6044. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6045. return
  6046. else:
  6047. self.save_source_file(name, filename)
  6048. if self.defaults["global_open_style"] is False:
  6049. self.file_opened.emit("Gerber", filename)
  6050. self.file_saved.emit("Gerber", filename)
  6051. def on_file_savescript(self):
  6052. """
  6053. Callback for menu item in Project context menu.
  6054. :return: None
  6055. """
  6056. self.defaults.report_usage("on_file_savescript")
  6057. App.log.debug("on_file_savescript()")
  6058. obj = self.collection.get_active()
  6059. if obj is None:
  6060. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6061. return
  6062. # Check for more compatible types and add as required
  6063. if not isinstance(obj, ScriptObject):
  6064. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6065. return
  6066. name = self.collection.get_active().options["name"]
  6067. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6068. try:
  6069. filename, _f = FCFileSaveDialog.get_saved_filename(
  6070. caption="Save Script source file",
  6071. directory=self.get_last_save_folder() + '/' + name,
  6072. ext_filter=_filter)
  6073. except TypeError:
  6074. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6075. filename = str(filename)
  6076. if filename == "":
  6077. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6078. return
  6079. else:
  6080. self.save_source_file(name, filename)
  6081. if self.defaults["global_open_style"] is False:
  6082. self.file_opened.emit("Script", filename)
  6083. self.file_saved.emit("Script", filename)
  6084. def on_file_savedocument(self):
  6085. """
  6086. Callback for menu item in Project context menu.
  6087. :return: None
  6088. """
  6089. self.defaults.report_usage("on_file_savedocument")
  6090. App.log.debug("on_file_savedocument()")
  6091. obj = self.collection.get_active()
  6092. if obj is None:
  6093. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6094. return
  6095. # Check for more compatible types and add as required
  6096. if not isinstance(obj, ScriptObject):
  6097. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6098. return
  6099. name = self.collection.get_active().options["name"]
  6100. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6101. try:
  6102. filename, _f = FCFileSaveDialog.get_saved_filename(
  6103. caption="Save Document source file",
  6104. directory=self.get_last_save_folder() + '/' + name,
  6105. ext_filter=_filter)
  6106. except TypeError:
  6107. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6108. ext_filter=_filter)
  6109. filename = str(filename)
  6110. if filename == "":
  6111. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6112. return
  6113. else:
  6114. self.save_source_file(name, filename)
  6115. if self.defaults["global_open_style"] is False:
  6116. self.file_opened.emit("Document", filename)
  6117. self.file_saved.emit("Document", filename)
  6118. def on_file_saveexcellon(self):
  6119. """
  6120. Callback for menu item in project context menu.
  6121. :return: None
  6122. """
  6123. self.defaults.report_usage("on_file_saveexcellon")
  6124. App.log.debug("on_file_saveexcellon()")
  6125. obj = self.collection.get_active()
  6126. if obj is None:
  6127. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6128. return
  6129. # Check for more compatible types and add as required
  6130. if not isinstance(obj, ExcellonObject):
  6131. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6132. return
  6133. name = self.collection.get_active().options["name"]
  6134. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6135. try:
  6136. filename, _f = FCFileSaveDialog.get_saved_filename(
  6137. caption=_("Save Excellon source file"),
  6138. directory=self.get_last_save_folder() + '/' + name,
  6139. ext_filter=_filter)
  6140. except TypeError:
  6141. filename, _f = FCFileSaveDialog.get_saved_filename(
  6142. caption=_("Save Excellon source file"), ext_filter=_filter)
  6143. filename = str(filename)
  6144. if filename == "":
  6145. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6146. return
  6147. else:
  6148. self.save_source_file(name, filename)
  6149. if self.defaults["global_open_style"] is False:
  6150. self.file_opened.emit("Excellon", filename)
  6151. self.file_saved.emit("Excellon", filename)
  6152. def on_file_exportexcellon(self):
  6153. """
  6154. Callback for menu item File->Export->Excellon.
  6155. :return: None
  6156. """
  6157. self.defaults.report_usage("on_file_exportexcellon")
  6158. App.log.debug("on_file_exportexcellon()")
  6159. obj = self.collection.get_active()
  6160. if obj is None:
  6161. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6162. return
  6163. # Check for more compatible types and add as required
  6164. if not isinstance(obj, ExcellonObject):
  6165. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6166. return
  6167. name = self.collection.get_active().options["name"]
  6168. _filter = self.defaults["excellon_save_filters"]
  6169. try:
  6170. filename, _f = FCFileSaveDialog.get_saved_filename(
  6171. caption=_("Export Excellon"),
  6172. directory=self.get_last_save_folder() + '/' + name,
  6173. ext_filter=_filter)
  6174. except TypeError:
  6175. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6176. filename = str(filename)
  6177. if filename == "":
  6178. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6179. return
  6180. else:
  6181. used_extension = filename.rpartition('.')[2]
  6182. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6183. self.export_excellon(name, filename)
  6184. if self.defaults["global_open_style"] is False:
  6185. self.file_opened.emit("Excellon", filename)
  6186. self.file_saved.emit("Excellon", filename)
  6187. def on_file_exportgerber(self):
  6188. """
  6189. Callback for menu item File->Export->Gerber.
  6190. :return: None
  6191. """
  6192. self.defaults.report_usage("on_file_exportgerber")
  6193. App.log.debug("on_file_exportgerber()")
  6194. obj = self.collection.get_active()
  6195. if obj is None:
  6196. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6197. return
  6198. # Check for more compatible types and add as required
  6199. if not isinstance(obj, GerberObject):
  6200. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6201. return
  6202. name = self.collection.get_active().options["name"]
  6203. _filter_ = self.defaults['gerber_save_filters']
  6204. try:
  6205. filename, _f = FCFileSaveDialog.get_saved_filename(
  6206. caption=_("Export Gerber"),
  6207. directory=self.get_last_save_folder() + '/' + name,
  6208. ext_filter=_filter_)
  6209. except TypeError:
  6210. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6211. filename = str(filename)
  6212. if filename == "":
  6213. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6214. return
  6215. else:
  6216. used_extension = filename.rpartition('.')[2]
  6217. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6218. self.export_gerber(name, filename)
  6219. if self.defaults["global_open_style"] is False:
  6220. self.file_opened.emit("Gerber", filename)
  6221. self.file_saved.emit("Gerber", filename)
  6222. def on_file_exportdxf(self):
  6223. """
  6224. Callback for menu item File->Export DXF.
  6225. :return: None
  6226. """
  6227. self.defaults.report_usage("on_file_exportdxf")
  6228. App.log.debug("on_file_exportdxf()")
  6229. obj = self.collection.get_active()
  6230. if obj is None:
  6231. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6232. msg = _("Please Select a Geometry object to export")
  6233. msgbox = QtWidgets.QMessageBox()
  6234. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6235. msgbox.setInformativeText(msg)
  6236. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6237. msgbox.setDefaultButton(bt_ok)
  6238. msgbox.exec_()
  6239. return
  6240. # Check for more compatible types and add as required
  6241. if not isinstance(obj, GeometryObject):
  6242. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6243. msgbox = QtWidgets.QMessageBox()
  6244. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6245. msgbox.setInformativeText(msg)
  6246. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6247. msgbox.setDefaultButton(bt_ok)
  6248. msgbox.exec_()
  6249. return
  6250. name = self.collection.get_active().options["name"]
  6251. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6252. try:
  6253. filename, _f = FCFileSaveDialog.get_saved_filename(
  6254. caption=_("Export DXF"),
  6255. directory=self.get_last_save_folder() + '/' + name,
  6256. ext_filter=_filter_)
  6257. except TypeError:
  6258. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6259. filename = str(filename)
  6260. if filename == "":
  6261. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6262. return
  6263. else:
  6264. self.export_dxf(name, filename)
  6265. if self.defaults["global_open_style"] is False:
  6266. self.file_opened.emit("DXF", filename)
  6267. self.file_saved.emit("DXF", filename)
  6268. def on_file_importsvg(self, type_of_obj):
  6269. """
  6270. Callback for menu item File->Import SVG.
  6271. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6272. :type type_of_obj: str
  6273. :return: None
  6274. """
  6275. self.defaults.report_usage("on_file_importsvg")
  6276. App.log.debug("on_file_importsvg()")
  6277. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6278. try:
  6279. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6280. directory=self.get_last_folder(), filter=_filter_)
  6281. except TypeError:
  6282. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6283. filter=_filter_)
  6284. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6285. type_of_obj = "geometry"
  6286. filenames = [str(filename) for filename in filenames]
  6287. if len(filenames) == 0:
  6288. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6289. else:
  6290. for filename in filenames:
  6291. if filename != '':
  6292. self.worker_task.emit({'fcn': self.import_svg,
  6293. 'params': [filename, type_of_obj]})
  6294. def on_file_importdxf(self, type_of_obj):
  6295. """
  6296. Callback for menu item File->Import DXF.
  6297. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6298. :type type_of_obj: str
  6299. :return: None
  6300. """
  6301. self.defaults.report_usage("on_file_importdxf")
  6302. App.log.debug("on_file_importdxf()")
  6303. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6304. try:
  6305. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6306. directory=self.get_last_folder(),
  6307. filter=_filter_)
  6308. except TypeError:
  6309. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6310. filter=_filter_)
  6311. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6312. type_of_obj = "geometry"
  6313. filenames = [str(filename) for filename in filenames]
  6314. if len(filenames) == 0:
  6315. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6316. else:
  6317. for filename in filenames:
  6318. if filename != '':
  6319. self.worker_task.emit({'fcn': self.import_dxf,
  6320. 'params': [filename, type_of_obj]})
  6321. # ###############################################################################################################
  6322. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6323. # ###############################################################################################################
  6324. def init_code_editor(self, name):
  6325. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6326. # add the tab if it was closed
  6327. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6328. self.text_editor_tab.setObjectName('text_editor_tab')
  6329. # delete the absolute and relative position and messages in the infobar
  6330. # self.ui.position_label.setText("")
  6331. # self.ui.rel_position_label.setText("")
  6332. # hide coordinates toolbars in the infobar while in DB
  6333. self.ui.coords_toolbar.hide()
  6334. self.ui.delta_coords_toolbar.hide()
  6335. self.toggle_codeeditor = True
  6336. self.text_editor_tab.code_editor.completer_enable = False
  6337. self.text_editor_tab.buttonRun.hide()
  6338. # make sure to keep a reference to the code editor
  6339. self.reference_code_editor = self.text_editor_tab.code_editor
  6340. # Switch plot_area to CNCJob tab
  6341. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6342. def on_view_source(self):
  6343. """
  6344. Called when the user wants to see the source file of the selected object
  6345. :return:
  6346. """
  6347. try:
  6348. obj = self.collection.get_active()
  6349. except Exception as e:
  6350. log.debug("App.on_view_source() --> %s" % str(e))
  6351. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6352. return 'fail'
  6353. if obj is None:
  6354. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6355. return 'fail'
  6356. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6357. self.proc_container.view.set_busy(_("Loading..."))
  6358. flt = "All Files (*.*)"
  6359. if obj.kind == 'gerber':
  6360. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6361. elif obj.kind == 'excellon':
  6362. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6363. elif obj.kind == 'cncjob':
  6364. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6365. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6366. # add the tab if it was closed
  6367. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6368. self.source_editor_tab.setObjectName('source_editor_tab')
  6369. # delete the absolute and relative position and messages in the infobar
  6370. # self.ui.position_label.setText("")
  6371. # self.ui.rel_position_label.setText("")
  6372. # hide coordinates toolbars in the infobar while in DB
  6373. self.ui.coords_toolbar.hide()
  6374. self.ui.delta_coords_toolbar.hide()
  6375. self.source_editor_tab.code_editor.completer_enable = False
  6376. self.source_editor_tab.buttonRun.hide()
  6377. # Switch plot_area to CNCJob tab
  6378. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6379. try:
  6380. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6381. except TypeError:
  6382. pass
  6383. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6384. try:
  6385. self.source_editor_tab.buttonSave.clicked.disconnect()
  6386. except TypeError:
  6387. pass
  6388. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6389. # then append the text from GCode to the text editor
  6390. if obj.kind == 'cncjob':
  6391. try:
  6392. file = obj.export_gcode(to_file=True)
  6393. if file == 'fail':
  6394. return 'fail'
  6395. except AttributeError:
  6396. self.inform.emit('[WARNING_NOTCL] %s' %
  6397. _("There is no selected object for which to see it's source file code."))
  6398. return 'fail'
  6399. else:
  6400. try:
  6401. file = StringIO(obj.source_file)
  6402. except (AttributeError, TypeError):
  6403. self.inform.emit('[WARNING_NOTCL] %s' %
  6404. _("There is no selected object for which to see it's source file code."))
  6405. return 'fail'
  6406. self.source_editor_tab.t_frame.hide()
  6407. try:
  6408. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6409. except Exception as e:
  6410. log.debug('App.on_view_source() -->%s' % str(e))
  6411. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6412. return
  6413. self.source_editor_tab.t_frame.show()
  6414. self.proc_container.view.set_idle()
  6415. # self.ui.show()
  6416. def on_toggle_code_editor(self):
  6417. self.defaults.report_usage("on_toggle_code_editor()")
  6418. if self.toggle_codeeditor is False:
  6419. self.init_code_editor(name=_("Code Editor"))
  6420. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6421. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6422. self.text_editor_tab.buttonSave.clicked.disconnect()
  6423. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6424. else:
  6425. for idx in range(self.ui.plot_tab_area.count()):
  6426. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6427. self.ui.plot_tab_area.closeTab(idx)
  6428. break
  6429. self.toggle_codeeditor = False
  6430. def on_code_editor_close(self):
  6431. self.toggle_codeeditor = False
  6432. def goto_text_line(self):
  6433. """
  6434. Will scroll a text to the specified text line.
  6435. :return: None
  6436. """
  6437. dia_box = Dialog_box(title=_("Go to Line ..."),
  6438. label=_("Line:"),
  6439. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6440. initial_text='')
  6441. try:
  6442. line = int(dia_box.location) - 1
  6443. except (ValueError, TypeError):
  6444. line = 0
  6445. if dia_box.ok:
  6446. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6447. # at the top of the window
  6448. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6449. # get the document() of the AppTextEditor
  6450. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6451. # create a Text Cursor based on the searched line
  6452. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6453. # set cursor of the code editor with the cursor at the searcehd line
  6454. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6455. def on_filenewscript(self, silent=False):
  6456. """
  6457. Will create a new script file and open it in the Code Editor
  6458. :param silent: if True will not display status messages
  6459. :return: None
  6460. """
  6461. if silent is False:
  6462. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6463. # delete the absolute and relative position and messages in the infobar
  6464. # self.ui.position_label.setText("")
  6465. # self.ui.rel_position_label.setText("")
  6466. # hide coordinates toolbars in the infobar while in DB
  6467. self.ui.coords_toolbar.hide()
  6468. self.ui.delta_coords_toolbar.hide()
  6469. self.app_obj.new_script_object()
  6470. # script_text = script_obj.source_file
  6471. #
  6472. # self.proc_container.view.set_busy(_("Loading..."))
  6473. # script_obj.script_editor_tab.t_frame.hide()
  6474. #
  6475. # script_obj.script_editor_tab.t_frame.show()
  6476. # self.proc_container.view.set_idle()
  6477. def on_fileopenscript(self, name=None, silent=False):
  6478. """
  6479. Will open a Tcl script file into the Code Editor
  6480. :param silent: if True will not display status messages
  6481. :param name: name of a Tcl script file to open
  6482. :return: None
  6483. """
  6484. self.defaults.report_usage("on_fileopenscript")
  6485. App.log.debug("on_fileopenscript()")
  6486. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6487. "All Files (*.*)"
  6488. if name:
  6489. filenames = [name]
  6490. else:
  6491. try:
  6492. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6493. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6494. except TypeError:
  6495. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6496. if len(filenames) == 0:
  6497. if silent is False:
  6498. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6499. else:
  6500. for filename in filenames:
  6501. if filename != '':
  6502. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6503. def on_fileopenscript_example(self, name=None, silent=False):
  6504. """
  6505. Will open a Tcl script file into the Code Editor
  6506. :param silent: if True will not display status messages
  6507. :param name: name of a Tcl script file to open
  6508. :return:
  6509. """
  6510. self.defaults.report_usage("on_fileopenscript_example")
  6511. log.debug("on_fileopenscript_example()")
  6512. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6513. "All Files (*.*)"
  6514. # test if the app was frozen and choose the path for the configuration file
  6515. if getattr(sys, "frozen", False) is True:
  6516. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6517. else:
  6518. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6519. if name:
  6520. filenames = [name]
  6521. else:
  6522. try:
  6523. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6524. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6525. except TypeError:
  6526. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6527. if len(filenames) == 0:
  6528. if silent is False:
  6529. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6530. else:
  6531. for filename in filenames:
  6532. if filename != '':
  6533. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6534. def on_filerunscript(self, name=None, silent=False):
  6535. """
  6536. File menu callback for loading and running a TCL script.
  6537. :param silent: if True will not display status messages
  6538. :param name: name of a Tcl script file to be run by FlatCAM
  6539. :return: None
  6540. """
  6541. self.defaults.report_usage("on_filerunscript")
  6542. App.log.debug("on_file_runscript()")
  6543. if name:
  6544. filename = name
  6545. if self.cmd_line_headless != 1:
  6546. self.splash.showMessage('%s: %ssec\n%s' %
  6547. (_("Canvas initialization started.\n"
  6548. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6549. _("Executing ScriptObject file.")
  6550. ),
  6551. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6552. color=QtGui.QColor("gray"))
  6553. else:
  6554. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6555. "All Files (*.*)"
  6556. try:
  6557. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6558. directory=self.get_last_folder(), filter=_filter_)
  6559. except TypeError:
  6560. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6561. # The Qt methods above will return a QString which can cause problems later.
  6562. # So far json.dump() will fail to serialize it.
  6563. filename = str(filename)
  6564. if filename == "":
  6565. if silent is False:
  6566. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6567. else:
  6568. if self.cmd_line_headless != 1:
  6569. if self.ui.shell_dock.isHidden():
  6570. self.ui.shell_dock.show()
  6571. try:
  6572. with open(filename, "r") as tcl_script:
  6573. cmd_line_shellfile_content = tcl_script.read()
  6574. if self.cmd_line_headless != 1:
  6575. self.shell.exec_command(cmd_line_shellfile_content)
  6576. else:
  6577. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6578. if silent is False:
  6579. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6580. except Exception as e:
  6581. log.debug("App.on_filerunscript() -> %s" % str(e))
  6582. sys.exit(2)
  6583. def on_file_saveproject(self, silent=False):
  6584. """
  6585. Callback for menu item File->Save Project. Saves the project to
  6586. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6587. if set to None. The project is saved by calling ``self.save_project()``.
  6588. :param silent: if True will not display status messages
  6589. :return: None
  6590. """
  6591. self.defaults.report_usage("on_file_saveproject")
  6592. if self.project_filename is None:
  6593. self.on_file_saveprojectas()
  6594. else:
  6595. self.worker_task.emit({'fcn': self.save_project,
  6596. 'params': [self.project_filename, silent]})
  6597. if self.defaults["global_open_style"] is False:
  6598. self.file_opened.emit("project", self.project_filename)
  6599. self.file_saved.emit("project", self.project_filename)
  6600. self.set_ui_title(name=self.project_filename)
  6601. self.should_we_save = False
  6602. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6603. """
  6604. Callback for menu item File->Save Project As... Opens a file
  6605. chooser and saves the project to the given file via
  6606. ``self.save_project()``.
  6607. :param make_copy if to be create a copy of the project; boolean
  6608. :param use_thread: if to be run in a separate thread; boolean
  6609. :param quit_action: if to be followed by quiting the application; boolean
  6610. :return: None
  6611. """
  6612. self.defaults.report_usage("on_file_saveprojectas")
  6613. self.date = str(datetime.today()).rpartition('.')[0]
  6614. self.date = ''.join(c for c in self.date if c not in ':-')
  6615. self.date = self.date.replace(' ', '_')
  6616. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6617. try:
  6618. filename, _f = FCFileSaveDialog.get_saved_filename(
  6619. caption=_("Save Project As ..."),
  6620. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6621. proj=_("Project")),
  6622. ext_filter=filter_
  6623. )
  6624. except TypeError:
  6625. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6626. filename = str(filename)
  6627. if filename == '':
  6628. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6629. return
  6630. if use_thread is True:
  6631. self.worker_task.emit({'fcn': self.save_project,
  6632. 'params': [filename, quit_action]})
  6633. else:
  6634. self.save_project(filename, quit_action)
  6635. # self.save_project(filename)
  6636. if self.defaults["global_open_style"] is False:
  6637. self.file_opened.emit("project", filename)
  6638. self.file_saved.emit("project", filename)
  6639. if not make_copy:
  6640. self.project_filename = filename
  6641. self.set_ui_title(name=self.project_filename)
  6642. self.should_we_save = False
  6643. def on_file_save_objects_pdf(self, use_thread=True):
  6644. self.date = str(datetime.today()).rpartition('.')[0]
  6645. self.date = ''.join(c for c in self.date if c not in ':-')
  6646. self.date = self.date.replace(' ', '_')
  6647. try:
  6648. obj_selection = self.collection.get_selected()
  6649. if len(obj_selection) == 1:
  6650. obj_name = str(obj_selection[0].options['name'])
  6651. else:
  6652. obj_name = _("FlatCAM objects print")
  6653. except AttributeError as err:
  6654. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6655. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6656. return
  6657. if not obj_selection:
  6658. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6659. return
  6660. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6661. try:
  6662. filename, _f = FCFileSaveDialog.get_saved_filename(
  6663. caption=_("Save Object as PDF ..."),
  6664. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6665. obj_name=obj_name,
  6666. date=self.date),
  6667. ext_filter=filter_
  6668. )
  6669. except TypeError:
  6670. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6671. filename = str(filename)
  6672. if filename == '':
  6673. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6674. return
  6675. if use_thread is True:
  6676. self.proc_container.new(_("Printing PDF ... Please wait."))
  6677. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6678. else:
  6679. self.save_pdf(filename, obj_selection)
  6680. # self.save_project(filename)
  6681. if self.defaults["global_open_style"] is False:
  6682. self.file_opened.emit("pdf", filename)
  6683. self.file_saved.emit("pdf", filename)
  6684. def save_pdf(self, file_name, obj_selection):
  6685. p_size = self.defaults['global_workspaceT']
  6686. orientation = self.defaults['global_workspace_orientation']
  6687. color = 'black'
  6688. transparency_level = 1.0
  6689. self.pagesize = {}
  6690. self.pagesize.update(
  6691. {
  6692. 'Bounds': None,
  6693. 'A0': (841 * mm, 1189 * mm),
  6694. 'A1': (594 * mm, 841 * mm),
  6695. 'A2': (420 * mm, 594 * mm),
  6696. 'A3': (297 * mm, 420 * mm),
  6697. 'A4': (210 * mm, 297 * mm),
  6698. 'A5': (148 * mm, 210 * mm),
  6699. 'A6': (105 * mm, 148 * mm),
  6700. 'A7': (74 * mm, 105 * mm),
  6701. 'A8': (52 * mm, 74 * mm),
  6702. 'A9': (37 * mm, 52 * mm),
  6703. 'A10': (26 * mm, 37 * mm),
  6704. 'B0': (1000 * mm, 1414 * mm),
  6705. 'B1': (707 * mm, 1000 * mm),
  6706. 'B2': (500 * mm, 707 * mm),
  6707. 'B3': (353 * mm, 500 * mm),
  6708. 'B4': (250 * mm, 353 * mm),
  6709. 'B5': (176 * mm, 250 * mm),
  6710. 'B6': (125 * mm, 176 * mm),
  6711. 'B7': (88 * mm, 125 * mm),
  6712. 'B8': (62 * mm, 88 * mm),
  6713. 'B9': (44 * mm, 62 * mm),
  6714. 'B10': (31 * mm, 44 * mm),
  6715. 'C0': (917 * mm, 1297 * mm),
  6716. 'C1': (648 * mm, 917 * mm),
  6717. 'C2': (458 * mm, 648 * mm),
  6718. 'C3': (324 * mm, 458 * mm),
  6719. 'C4': (229 * mm, 324 * mm),
  6720. 'C5': (162 * mm, 229 * mm),
  6721. 'C6': (114 * mm, 162 * mm),
  6722. 'C7': (81 * mm, 114 * mm),
  6723. 'C8': (57 * mm, 81 * mm),
  6724. 'C9': (40 * mm, 57 * mm),
  6725. 'C10': (28 * mm, 40 * mm),
  6726. # American paper sizes
  6727. 'LETTER': (8.5 * inch, 11 * inch),
  6728. 'LEGAL': (8.5 * inch, 14 * inch),
  6729. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6730. # From https://en.wikipedia.org/wiki/Paper_size
  6731. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6732. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6733. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6734. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6735. 'LEDGER': (17 * inch, 11 * inch),
  6736. }
  6737. )
  6738. exported_svg = []
  6739. for obj in obj_selection:
  6740. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6741. scale_factor_x=None, scale_factor_y=None,
  6742. skew_factor_x=None, skew_factor_y=None,
  6743. mirror=None)
  6744. if obj.kind.lower() == 'gerber':
  6745. # color = self.defaults["gerber_plot_fill"][:-2]
  6746. color = obj.fill_color[:-2]
  6747. elif obj.kind.lower() == 'excellon':
  6748. color = '#C40000'
  6749. elif obj.kind.lower() == 'geometry':
  6750. color = self.defaults["global_draw_color"]
  6751. # Change the attributes of the exported SVG
  6752. # We don't need stroke-width
  6753. # We set opacity to maximum
  6754. # We set the colour to WHITE
  6755. root = ET.fromstring(svg_obj)
  6756. for child in root:
  6757. child.set('fill', str(color))
  6758. child.set('opacity', str(transparency_level))
  6759. child.set('stroke', str(color))
  6760. exported_svg.append(ET.tostring(root))
  6761. xmin = Inf
  6762. ymin = Inf
  6763. xmax = -Inf
  6764. ymax = -Inf
  6765. for obj in obj_selection:
  6766. try:
  6767. gxmin, gymin, gxmax, gymax = obj.bounds()
  6768. xmin = min([xmin, gxmin])
  6769. ymin = min([ymin, gymin])
  6770. xmax = max([xmax, gxmax])
  6771. ymax = max([ymax, gymax])
  6772. except Exception as e:
  6773. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6774. # Determine bounding area for svg export
  6775. bounds = [xmin, ymin, xmax, ymax]
  6776. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6777. # This contain the measure units
  6778. uom = obj_selection[0].units.lower()
  6779. # Define a boundary around SVG of about 1.0mm (~39mils)
  6780. if uom in "mm":
  6781. boundary = 1.0
  6782. else:
  6783. boundary = 0.0393701
  6784. # Convert everything to strings for use in the xml doc
  6785. svgwidth = str(size[0] + (2 * boundary))
  6786. svgheight = str(size[1] + (2 * boundary))
  6787. minx = str(bounds[0] - boundary)
  6788. miny = str(bounds[1] + boundary + size[1])
  6789. # Add a SVG Header and footer to the svg output from shapely
  6790. # The transform flips the Y Axis so that everything renders
  6791. # properly within svg apps such as inkscape
  6792. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6793. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6794. svg_header += 'width="' + svgwidth + uom + '" '
  6795. svg_header += 'height="' + svgheight + uom + '" '
  6796. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6797. svg_header += '>'
  6798. svg_header += '<g transform="scale(1,-1)">'
  6799. svg_footer = '</g> </svg>'
  6800. svg_elem = str(svg_header)
  6801. for svg_item in exported_svg:
  6802. svg_elem += str(svg_item)
  6803. svg_elem += str(svg_footer)
  6804. # Parse the xml through a xml parser just to add line feeds
  6805. # and to make it look more pretty for the output
  6806. doc = parse_xml_string(svg_elem)
  6807. doc_final = doc.toprettyxml()
  6808. try:
  6809. if self.defaults['units'].upper() == 'IN':
  6810. unit = inch
  6811. else:
  6812. unit = mm
  6813. doc_final = StringIO(doc_final)
  6814. drawing = svg2rlg(doc_final)
  6815. if p_size == 'Bounds':
  6816. renderPDF.drawToFile(drawing, file_name)
  6817. else:
  6818. if orientation == 'p':
  6819. page_size = portrait(self.pagesize[p_size])
  6820. else:
  6821. page_size = landscape(self.pagesize[p_size])
  6822. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6823. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6824. renderPDF.draw(drawing, my_canvas, 0, 0)
  6825. my_canvas.save()
  6826. except Exception as e:
  6827. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6828. return 'fail'
  6829. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6830. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6831. """
  6832. Exports a Geometry Object to an SVG file.
  6833. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6834. :param filename: Path to the SVG file to save to.
  6835. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6836. :return:
  6837. """
  6838. self.defaults.report_usage("export_svg()")
  6839. if filename is None:
  6840. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6841. is not None else self.defaults["global_last_folder"]
  6842. self.log.debug("export_svg()")
  6843. try:
  6844. obj = self.collection.get_by_name(str(obj_name))
  6845. except Exception:
  6846. # TODO: The return behavior has not been established... should raise exception?
  6847. return "Could not retrieve object: %s" % obj_name
  6848. with self.proc_container.new(_("Exporting SVG")) as proc:
  6849. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6850. # Determine bounding area for svg export
  6851. bounds = obj.bounds()
  6852. size = obj.size()
  6853. # Convert everything to strings for use in the xml doc
  6854. svgwidth = str(size[0])
  6855. svgheight = str(size[1])
  6856. minx = str(bounds[0])
  6857. miny = str(bounds[1] - size[1])
  6858. uom = obj.units.lower()
  6859. # Add a SVG Header and footer to the svg output from shapely
  6860. # The transform flips the Y Axis so that everything renders
  6861. # properly within svg apps such as inkscape
  6862. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6863. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6864. svg_header += 'width="' + svgwidth + uom + '" '
  6865. svg_header += 'height="' + svgheight + uom + '" '
  6866. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6867. svg_header += '<g transform="scale(1,-1)">'
  6868. svg_footer = '</g> </svg>'
  6869. svg_elem = svg_header + exported_svg + svg_footer
  6870. # Parse the xml through a xml parser just to add line feeds
  6871. # and to make it look more pretty for the output
  6872. svgcode = parse_xml_string(svg_elem)
  6873. svgcode = svgcode.toprettyxml()
  6874. try:
  6875. with open(filename, 'w') as fp:
  6876. fp.write(svgcode)
  6877. except PermissionError:
  6878. self.inform.emit('[WARNING] %s' %
  6879. _("Permission denied, saving not possible.\n"
  6880. "Most likely another app is holding the file open and not accessible."))
  6881. return 'fail'
  6882. if self.defaults["global_open_style"] is False:
  6883. self.file_opened.emit("SVG", filename)
  6884. self.file_saved.emit("SVG", filename)
  6885. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6886. def save_source_file(self, obj_name, filename, use_thread=True):
  6887. """
  6888. Exports a FlatCAM Object to an Gerber/Excellon file.
  6889. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6890. :param filename: Path to the Gerber file to save to.
  6891. :param use_thread: if to be run in a separate thread
  6892. :return:
  6893. """
  6894. self.defaults.report_usage("save source file()")
  6895. if filename is None:
  6896. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6897. is not None else self.defaults["global_last_folder"]
  6898. self.log.debug("save source file()")
  6899. obj = self.collection.get_by_name(obj_name)
  6900. file_string = StringIO(obj.source_file)
  6901. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6902. if file_string.getvalue() == '':
  6903. self.inform.emit('[ERROR_NOTCL] %s' %
  6904. _("Save cancelled because source file is empty. Try to export the file."))
  6905. return 'fail'
  6906. try:
  6907. with open(filename, 'w') as file:
  6908. file.writelines('G04*\n')
  6909. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6910. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6911. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6912. file.writelines('G04 Created on : %s*\n' % time_string)
  6913. for line in file_string:
  6914. file.writelines(line)
  6915. except PermissionError:
  6916. self.inform.emit('[WARNING] %s' %
  6917. _("Permission denied, saving not possible.\n"
  6918. "Most likely another app is holding the file open and not accessible."))
  6919. return 'fail'
  6920. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6921. """
  6922. Exports a Excellon Object to an Excellon file.
  6923. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6924. :param filename: Path to the Excellon file to save to.
  6925. :param local_use:
  6926. :param use_thread: if to be run in a separate thread
  6927. :return:
  6928. """
  6929. self.defaults.report_usage("export_excellon()")
  6930. if filename is None:
  6931. if self.defaults["global_last_save_folder"]:
  6932. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6933. else:
  6934. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6935. self.log.debug("export_excellon()")
  6936. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6937. self.defaults["excellon_exp_decimals"]
  6938. )
  6939. if local_use is None:
  6940. try:
  6941. obj = self.collection.get_by_name(str(obj_name))
  6942. except Exception:
  6943. return "Could not retrieve object: %s" % obj_name
  6944. else:
  6945. obj = local_use
  6946. if not isinstance(obj, ExcellonObject):
  6947. self.inform.emit('[ERROR_NOTCL] %s' %
  6948. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6949. return
  6950. # updated units
  6951. eunits = self.defaults["excellon_exp_units"]
  6952. ewhole = self.defaults["excellon_exp_integer"]
  6953. efract = self.defaults["excellon_exp_decimals"]
  6954. ezeros = self.defaults["excellon_exp_zeros"]
  6955. eformat = self.defaults["excellon_exp_format"]
  6956. slot_type = self.defaults["excellon_exp_slot_type"]
  6957. fc_units = self.defaults['units'].upper()
  6958. if fc_units == 'MM':
  6959. factor = 1 if eunits == 'METRIC' else 0.03937
  6960. else:
  6961. factor = 25.4 if eunits == 'METRIC' else 1
  6962. def make_excellon():
  6963. try:
  6964. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6965. header = 'M48\n'
  6966. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6967. (str(self.version), str(self.version_date))
  6968. header += ';Filename: %s' % str(obj_name) + '\n'
  6969. header += ';Created on : %s' % time_str + '\n'
  6970. if eformat == 'dec':
  6971. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6972. header += eunits + '\n'
  6973. for tool in obj.tools:
  6974. if eunits == 'METRIC':
  6975. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6976. tool=str(tool),
  6977. dec=2)
  6978. else:
  6979. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6980. tool=str(tool),
  6981. dec=4)
  6982. else:
  6983. if ezeros == 'LZ':
  6984. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6985. form='ndec', e_zeros='LZ', factor=factor,
  6986. slot_type=slot_type)
  6987. header += '%s,%s\n' % (eunits, 'LZ')
  6988. header += format_exc
  6989. for tool in obj.tools:
  6990. if eunits == 'METRIC':
  6991. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6992. float(obj.tools[tool]['tooldia']) * factor,
  6993. tool=str(tool),
  6994. dec=2)
  6995. else:
  6996. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6997. float(obj.tools[tool]['tooldia']) * factor,
  6998. tool=str(tool),
  6999. dec=4)
  7000. else:
  7001. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7002. form='ndec', e_zeros='TZ', factor=factor,
  7003. slot_type=slot_type)
  7004. header += '%s,%s\n' % (eunits, 'TZ')
  7005. header += format_exc
  7006. for tool in obj.tools:
  7007. if eunits == 'METRIC':
  7008. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7009. float(obj.tools[tool]['tooldia']) * factor,
  7010. tool=str(tool),
  7011. dec=2)
  7012. else:
  7013. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7014. float(obj.tools[tool]['tooldia']) * factor,
  7015. tool=str(tool),
  7016. dec=4)
  7017. header += '%\n'
  7018. footer = 'M30\n'
  7019. exported_excellon = header
  7020. exported_excellon += excellon_code
  7021. exported_excellon += footer
  7022. if local_use is None:
  7023. try:
  7024. with open(filename, 'w') as fp:
  7025. fp.write(exported_excellon)
  7026. except PermissionError:
  7027. self.inform.emit('[WARNING] %s' %
  7028. _("Permission denied, saving not possible.\n"
  7029. "Most likely another app is holding the file open and not accessible."))
  7030. return 'fail'
  7031. if self.defaults["global_open_style"] is False:
  7032. self.file_opened.emit("Excellon", filename)
  7033. self.file_saved.emit("Excellon", filename)
  7034. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7035. else:
  7036. return exported_excellon
  7037. except Exception as e:
  7038. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7039. return 'fail'
  7040. if use_thread is True:
  7041. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7042. def job_thread_exc(app_obj):
  7043. ret = make_excellon()
  7044. if ret == 'fail':
  7045. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7046. return
  7047. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7048. else:
  7049. eret = make_excellon()
  7050. if eret == 'fail':
  7051. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7052. return 'fail'
  7053. if local_use is not None:
  7054. return eret
  7055. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7056. """
  7057. Exports a Gerber Object to an Gerber file.
  7058. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7059. :param filename: Path to the Gerber file to save to.
  7060. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7061. When not None, the value will be the actual Gerber object for which to create
  7062. the Gerber code
  7063. :param use_thread: if to be run in a separate thread
  7064. :return:
  7065. """
  7066. self.defaults.report_usage("export_gerber()")
  7067. if filename is None:
  7068. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7069. is not None else self.defaults["global_last_folder"]
  7070. self.log.debug("export_gerber()")
  7071. if local_use is None:
  7072. try:
  7073. obj = self.collection.get_by_name(str(obj_name))
  7074. except Exception:
  7075. return 'fail'
  7076. else:
  7077. obj = local_use
  7078. # updated units
  7079. gunits = self.defaults["gerber_exp_units"]
  7080. gwhole = self.defaults["gerber_exp_integer"]
  7081. gfract = self.defaults["gerber_exp_decimals"]
  7082. gzeros = self.defaults["gerber_exp_zeros"]
  7083. fc_units = self.defaults['units'].upper()
  7084. if fc_units == 'MM':
  7085. factor = 1 if gunits == 'MM' else 0.03937
  7086. else:
  7087. factor = 25.4 if gunits == 'MM' else 1
  7088. def make_gerber():
  7089. try:
  7090. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7091. header = 'G04*\n'
  7092. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7093. (str(self.version), str(self.version_date))
  7094. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7095. header += 'G04 Created on : %s*' % time_str + '\n'
  7096. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7097. header += "%MO{units}*%\n".format(units=gunits)
  7098. for apid in obj.apertures:
  7099. if obj.apertures[apid]['type'] == 'C':
  7100. header += "%ADD{apid}{type},{size}*%\n".format(
  7101. apid=str(apid),
  7102. type='C',
  7103. size=(factor * obj.apertures[apid]['size'])
  7104. )
  7105. elif obj.apertures[apid]['type'] == 'R':
  7106. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7107. apid=str(apid),
  7108. type='R',
  7109. width=(factor * obj.apertures[apid]['width']),
  7110. height=(factor * obj.apertures[apid]['height'])
  7111. )
  7112. elif obj.apertures[apid]['type'] == 'O':
  7113. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7114. apid=str(apid),
  7115. type='O',
  7116. width=(factor * obj.apertures[apid]['width']),
  7117. height=(factor * obj.apertures[apid]['height'])
  7118. )
  7119. header += '\n'
  7120. # obsolete units but some software may need it
  7121. if gunits == 'IN':
  7122. header += 'G70*\n'
  7123. else:
  7124. header += 'G71*\n'
  7125. # Absolute Mode
  7126. header += 'G90*\n'
  7127. header += 'G01*\n'
  7128. # positive polarity
  7129. header += '%LPD*%\n'
  7130. footer = 'M02*\n'
  7131. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7132. exported_gerber = header
  7133. exported_gerber += gerber_code
  7134. exported_gerber += footer
  7135. if local_use is None:
  7136. try:
  7137. with open(filename, 'w') as fp:
  7138. fp.write(exported_gerber)
  7139. except PermissionError:
  7140. self.inform.emit('[WARNING] %s' %
  7141. _("Permission denied, saving not possible.\n"
  7142. "Most likely another app is holding the file open and not accessible."))
  7143. return 'fail'
  7144. if self.defaults["global_open_style"] is False:
  7145. self.file_opened.emit("Gerber", filename)
  7146. self.file_saved.emit("Gerber", filename)
  7147. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7148. else:
  7149. return exported_gerber
  7150. except Exception as e:
  7151. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7152. return 'fail'
  7153. if use_thread is True:
  7154. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7155. def job_thread_grb(app_obj):
  7156. ret = make_gerber()
  7157. if ret == 'fail':
  7158. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7159. return
  7160. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7161. else:
  7162. gret = make_gerber()
  7163. if gret == 'fail':
  7164. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7165. return 'fail'
  7166. if local_use is not None:
  7167. return gret
  7168. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7169. """
  7170. Exports a Geometry Object to an DXF file.
  7171. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7172. :param filename: Path to the DXF file to save to.
  7173. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7174. When not None, the value will be the actual Geometry object for which to create
  7175. the Geometry/DXF code
  7176. :param use_thread: if to be run in a separate thread
  7177. :return:
  7178. """
  7179. self.defaults.report_usage("export_dxf()")
  7180. if filename is None:
  7181. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7182. is not None else self.defaults["global_last_folder"]
  7183. self.log.debug("export_dxf()")
  7184. if local_use is None:
  7185. try:
  7186. obj = self.collection.get_by_name(str(obj_name))
  7187. except Exception:
  7188. return 'fail'
  7189. else:
  7190. obj = local_use
  7191. def make_dxf():
  7192. try:
  7193. dxf_code = obj.export_dxf()
  7194. if local_use is None:
  7195. try:
  7196. dxf_code.saveas(filename)
  7197. except PermissionError:
  7198. self.inform.emit('[WARNING] %s' %
  7199. _("Permission denied, saving not possible.\n"
  7200. "Most likely another app is holding the file open and not accessible."))
  7201. return 'fail'
  7202. if self.defaults["global_open_style"] is False:
  7203. self.file_opened.emit("DXF", filename)
  7204. self.file_saved.emit("DXF", filename)
  7205. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7206. else:
  7207. return dxf_code
  7208. except Exception as e:
  7209. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7210. return 'fail'
  7211. if use_thread is True:
  7212. with self.proc_container.new(_("Exporting DXF")) as proc:
  7213. def job_thread_exc(app_obj):
  7214. ret_dxf_val = make_dxf()
  7215. if ret_dxf_val == 'fail':
  7216. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7217. return
  7218. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7219. else:
  7220. ret = make_dxf()
  7221. if ret == 'fail':
  7222. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7223. return
  7224. if local_use is not None:
  7225. return ret
  7226. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7227. """
  7228. Adds a new Geometry Object to the projects and populates
  7229. it with shapes extracted from the SVG file.
  7230. :param plot: If True then the resulting object will be plotted on canvas
  7231. :param filename: Path to the SVG file.
  7232. :param geo_type: Type of FlatCAM object that will be created from SVG
  7233. :param outname: The name given to the resulting FlatCAM object
  7234. :return:
  7235. """
  7236. self.defaults.report_usage("import_svg()")
  7237. log.debug("App.import_svg()")
  7238. obj_type = ""
  7239. if geo_type is None or geo_type == "geometry":
  7240. obj_type = "geometry"
  7241. elif geo_type == "gerber":
  7242. obj_type = "gerber"
  7243. else:
  7244. self.inform.emit('[ERROR_NOTCL] %s' %
  7245. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7246. return
  7247. units = self.defaults['units'].upper()
  7248. def obj_init(geo_obj, app_obj):
  7249. if obj_type == "geometry":
  7250. geo_obj.import_svg(filename, obj_type, units=units)
  7251. elif obj_type == "gerber":
  7252. geo_obj.import_svg(filename, obj_type, units=units)
  7253. geo_obj.multigeo = True
  7254. with open(filename) as f:
  7255. file_content = f.read()
  7256. geo_obj.source_file = file_content
  7257. with self.proc_container.new(_("Importing SVG")) as proc:
  7258. # Object name
  7259. name = outname or filename.split('/')[-1].split('\\')[-1]
  7260. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7261. if ret == 'fail':
  7262. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7263. return 'fail'
  7264. # Register recent file
  7265. self.file_opened.emit("svg", filename)
  7266. # appGUI feedback
  7267. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7268. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7269. """
  7270. Adds a new Geometry Object to the projects and populates
  7271. it with shapes extracted from the DXF file.
  7272. :param filename: Path to the DXF file.
  7273. :param geo_type: Type of FlatCAM object that will be created from DXF
  7274. :param outname: Name for the imported Geometry
  7275. :param plot: If True then the resulting object will be plotted on canvas
  7276. :return:
  7277. """
  7278. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7279. obj_type = ""
  7280. if geo_type is None or geo_type == "geometry":
  7281. obj_type = "geometry"
  7282. elif geo_type == "gerber":
  7283. obj_type = geo_type
  7284. else:
  7285. self.inform.emit('[ERROR_NOTCL] %s' %
  7286. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7287. return
  7288. units = self.defaults['units'].upper()
  7289. def obj_init(geo_obj, app_obj):
  7290. if obj_type == "geometry":
  7291. geo_obj.import_dxf_as_geo(filename, units=units)
  7292. elif obj_type == "gerber":
  7293. geo_obj.import_dxf_as_gerber(filename, units=units)
  7294. else:
  7295. return "fail"
  7296. geo_obj.multigeo = True
  7297. with open(filename) as f:
  7298. file_content = f.read()
  7299. geo_obj.source_file = file_content
  7300. with self.proc_container.new(_("Importing DXF")):
  7301. # Object name
  7302. name = outname or filename.split('/')[-1].split('\\')[-1]
  7303. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7304. if ret == 'fail':
  7305. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7306. return 'fail'
  7307. # Register recent file
  7308. self.file_opened.emit("dxf", filename)
  7309. # appGUI feedback
  7310. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7311. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7312. """
  7313. Opens a Gerber file, parses it and creates a new object for
  7314. it in the program. Thread-safe.
  7315. :param outname: Name of the resulting object. None causes the
  7316. name to be that of the file. Str.
  7317. :param filename: Gerber file filename
  7318. :type filename: str
  7319. :param plot: boolean, to plot or not the resulting object
  7320. :param from_tcl: True if run from Tcl Shell
  7321. :return: None
  7322. """
  7323. # How the object should be initialized
  7324. def obj_init(gerber_obj, app_obj):
  7325. assert isinstance(gerber_obj, GerberObject), \
  7326. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7327. # Opening the file happens here
  7328. try:
  7329. gerber_obj.parse_file(filename)
  7330. except IOError:
  7331. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7332. return "fail"
  7333. except ParseError as err:
  7334. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7335. app_obj.log.error(str(err))
  7336. return "fail"
  7337. except Exception as e:
  7338. log.debug("App.open_gerber() --> %s" % str(e))
  7339. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7340. msg += traceback.format_exc()
  7341. app_obj.inform.emit(msg)
  7342. return "fail"
  7343. if gerber_obj.is_empty():
  7344. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7345. _("Object is not Gerber file or empty. Aborting object creation."))
  7346. return "fail"
  7347. App.log.debug("open_gerber()")
  7348. with self.proc_container.new(_("Opening Gerber")):
  7349. # Object name
  7350. name = outname or filename.split('/')[-1].split('\\')[-1]
  7351. # # ## Object creation # ##
  7352. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7353. if ret_val == 'fail':
  7354. if from_tcl:
  7355. filename = self.defaults['global_tcl_path'] + '/' + name
  7356. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7357. if ret_val == 'fail':
  7358. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7359. return 'fail'
  7360. # Register recent file
  7361. self.file_opened.emit("gerber", filename)
  7362. # appGUI feedback
  7363. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7364. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7365. """
  7366. Opens an Excellon file, parses it and creates a new object for
  7367. it in the program. Thread-safe.
  7368. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7369. :param filename: Excellon file filename
  7370. :type filename: str
  7371. :param plot: boolean, to plot or not the resulting object
  7372. :param from_tcl: True if run from Tcl Shell
  7373. :return: None
  7374. """
  7375. App.log.debug("open_excellon()")
  7376. # How the object should be initialized
  7377. def obj_init(excellon_obj, app_obj):
  7378. try:
  7379. ret = excellon_obj.parse_file(filename=filename)
  7380. if ret == "fail":
  7381. log.debug("Excellon parsing failed.")
  7382. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7383. return "fail"
  7384. except IOError:
  7385. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7386. log.debug("Could not open Excellon object.")
  7387. return "fail"
  7388. except Exception:
  7389. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7390. msg += traceback.format_exc()
  7391. app_obj.inform.emit(msg)
  7392. return "fail"
  7393. ret = excellon_obj.create_geometry()
  7394. if ret == 'fail':
  7395. log.debug("Could not create geometry for Excellon object.")
  7396. return "fail"
  7397. for tool in excellon_obj.tools:
  7398. if excellon_obj.tools[tool]['solid_geometry']:
  7399. return
  7400. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7401. return "fail"
  7402. with self.proc_container.new(_("Opening Excellon.")):
  7403. # Object name
  7404. name = outname or filename.split('/')[-1].split('\\')[-1]
  7405. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7406. if ret_val == 'fail':
  7407. if from_tcl:
  7408. filename = self.defaults['global_tcl_path'] + '/' + name
  7409. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7410. if ret_val == 'fail':
  7411. self.inform.emit('[ERROR_NOTCL] %s' %
  7412. _('Open Excellon file failed. Probable not an Excellon file.'))
  7413. return
  7414. # Register recent file
  7415. self.file_opened.emit("excellon", filename)
  7416. # appGUI feedback
  7417. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7418. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7419. """
  7420. Opens a G-gcode file, parses it and creates a new object for
  7421. it in the program. Thread-safe.
  7422. :param filename: G-code file filename
  7423. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7424. :param force_parsing:
  7425. :param plot: If True plot the object on canvas
  7426. :param from_tcl: True if run from Tcl Shell
  7427. :return: None
  7428. """
  7429. App.log.debug("open_gcode()")
  7430. # How the object should be initialized
  7431. def obj_init(job_obj, app_obj_):
  7432. """
  7433. :param job_obj: the resulting object
  7434. :type app_obj_: App
  7435. """
  7436. assert isinstance(app_obj_, App), \
  7437. "Initializer expected App, got %s" % type(app_obj_)
  7438. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7439. try:
  7440. f = open(filename)
  7441. gcode = f.read()
  7442. f.close()
  7443. except IOError:
  7444. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7445. return "fail"
  7446. job_obj.gcode = gcode
  7447. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7448. if gcode_ret == "fail":
  7449. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7450. return "fail"
  7451. job_obj.create_geometry()
  7452. with self.proc_container.new(_("Opening G-Code.")):
  7453. # Object name
  7454. name = outname or filename.split('/')[-1].split('\\')[-1]
  7455. # New object creation and file processing
  7456. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7457. if ret_val == 'fail':
  7458. if from_tcl:
  7459. filename = self.defaults['global_tcl_path'] + '/' + name
  7460. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7461. if ret_val == 'fail':
  7462. self.inform.emit('[ERROR_NOTCL] %s' %
  7463. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7464. "Try to load it from File menu.\n "
  7465. "Attempting to create a FlatCAM CNCJob Object from "
  7466. "G-Code file failed during processing"))
  7467. return "fail"
  7468. # Register recent file
  7469. self.file_opened.emit("cncjob", filename)
  7470. # appGUI feedback
  7471. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7472. def open_hpgl2(self, filename, outname=None):
  7473. """
  7474. Opens a HPGL2 file, parses it and creates a new object for
  7475. it in the program. Thread-safe.
  7476. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7477. :param filename: HPGL2 file filename
  7478. :return: None
  7479. """
  7480. filename = filename
  7481. # How the object should be initialized
  7482. def obj_init(geo_obj, app_obj):
  7483. assert isinstance(geo_obj, GeometryObject), \
  7484. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7485. # Opening the file happens here
  7486. obj = HPGL2(self)
  7487. try:
  7488. HPGL2.parse_file(obj, filename)
  7489. except IOError:
  7490. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7491. return "fail"
  7492. except ParseError as err:
  7493. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7494. app_obj.log.error(str(err))
  7495. return "fail"
  7496. except Exception as e:
  7497. log.debug("App.open_hpgl2() --> %s" % str(e))
  7498. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7499. msg += traceback.format_exc()
  7500. app_obj.inform.emit(msg)
  7501. return "fail"
  7502. geo_obj.multigeo = True
  7503. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7504. geo_obj.tools = deepcopy(obj.tools)
  7505. geo_obj.source_file = deepcopy(obj.source_file)
  7506. del obj
  7507. if not geo_obj.solid_geometry:
  7508. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7509. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7510. return "fail"
  7511. App.log.debug("open_hpgl2()")
  7512. with self.proc_container.new(_("Opening HPGL2")):
  7513. # Object name
  7514. name = outname or filename.split('/')[-1].split('\\')[-1]
  7515. # # ## Object creation # ##
  7516. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7517. if ret == 'fail':
  7518. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7519. return 'fail'
  7520. # Register recent file
  7521. self.file_opened.emit("geometry", filename)
  7522. # appGUI feedback
  7523. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7524. def open_script(self, filename, outname=None, silent=False):
  7525. """
  7526. Opens a Script file, parses it and creates a new object for
  7527. it in the program. Thread-safe.
  7528. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7529. :param filename: Script file filename
  7530. :param silent: If True there will be no messages printed to StatusBar
  7531. :return: None
  7532. """
  7533. def obj_init(script_obj, app_obj):
  7534. assert isinstance(script_obj, ScriptObject), \
  7535. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7536. if silent is False:
  7537. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7538. try:
  7539. script_obj.parse_file(filename)
  7540. except IOError:
  7541. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7542. return "fail"
  7543. except ParseError as err:
  7544. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7545. app_obj.log.error(str(err))
  7546. return "fail"
  7547. except Exception as e:
  7548. log.debug("App.open_script() -> %s" % str(e))
  7549. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7550. msg += traceback.format_exc()
  7551. app_obj.inform.emit(msg)
  7552. return "fail"
  7553. App.log.debug("open_script()")
  7554. with self.proc_container.new(_("Opening TCL Script...")):
  7555. # Object name
  7556. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7557. # Object creation
  7558. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7559. if ret_val == 'fail':
  7560. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7561. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7562. if ret_val == 'fail':
  7563. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7564. return 'fail'
  7565. # Register recent file
  7566. self.file_opened.emit("script", filename)
  7567. # appGUI feedback
  7568. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7569. def open_config_file(self, filename, run_from_arg=None):
  7570. """
  7571. Loads a config file from the specified file.
  7572. :param filename: Name of the file from which to load.
  7573. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7574. :return: None
  7575. """
  7576. App.log.debug("Opening config file: " + filename)
  7577. if run_from_arg:
  7578. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7579. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7580. _("Opening FlatCAM Config file.")),
  7581. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7582. color=QtGui.QColor("gray"))
  7583. # # add the tab if it was closed
  7584. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7585. # # first clear previous text in text editor (if any)
  7586. # self.ui.text_editor_tab.code_editor.clear()
  7587. #
  7588. # # Switch plot_area to CNCJob tab
  7589. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7590. # close the Code editor if already open
  7591. if self.toggle_codeeditor:
  7592. self.on_toggle_code_editor()
  7593. self.on_toggle_code_editor()
  7594. try:
  7595. if filename:
  7596. f = QtCore.QFile(filename)
  7597. if f.open(QtCore.QIODevice.ReadOnly):
  7598. stream = QtCore.QTextStream(f)
  7599. code_edited = stream.readAll()
  7600. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7601. f.close()
  7602. except IOError:
  7603. App.log.error("Failed to open config file: %s" % filename)
  7604. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7605. (_("Failed to open config file"), filename))
  7606. return
  7607. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7608. """
  7609. Loads a project from the specified file.
  7610. 1) Loads and parses file
  7611. 2) Registers the file as recently opened.
  7612. 3) Calls on_file_new()
  7613. 4) Updates options
  7614. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7615. 6) Calls plot_all() if plot=True
  7616. :param filename: Name of the file from which to load.
  7617. :param run_from_arg: True if run for arguments
  7618. :param plot: If True plot all objects in the project
  7619. :param cli: Run from command line
  7620. :param from_tcl: True if run from Tcl Sehll
  7621. :return: None
  7622. """
  7623. App.log.debug("Opening project: " + filename)
  7624. # block autosaving while a project is loaded
  7625. self.block_autosave = True
  7626. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7627. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7628. if cli is None:
  7629. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7630. if run_from_arg:
  7631. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7632. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7633. _("Opening FlatCAM Project file.")),
  7634. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7635. color=QtGui.QColor("gray"))
  7636. # Open and parse an uncompressed Project file
  7637. try:
  7638. f = open(filename, 'r')
  7639. except IOError:
  7640. if from_tcl:
  7641. name = filename.split('/')[-1].split('\\')[-1]
  7642. filename = self.defaults['global_tcl_path'] + '/' + name
  7643. try:
  7644. f = open(filename, 'r')
  7645. except IOError:
  7646. log.error("Failed to open project file: %s" % filename)
  7647. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7648. return
  7649. else:
  7650. log.error("Failed to open project file: %s" % filename)
  7651. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7652. return
  7653. try:
  7654. d = json.load(f, object_hook=dict2obj)
  7655. except Exception as e:
  7656. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7657. (filename, str(e)))
  7658. f.close()
  7659. # Open and parse a compressed Project file
  7660. try:
  7661. with lzma.open(filename) as f:
  7662. file_content = f.read().decode('utf-8')
  7663. d = json.loads(file_content, object_hook=dict2obj)
  7664. except Exception as e:
  7665. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7666. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7667. return
  7668. # Clear the current project
  7669. # # NOT THREAD SAFE # ##
  7670. if run_from_arg is True:
  7671. pass
  7672. elif cli is True:
  7673. self.delete_selection_shape()
  7674. else:
  7675. self.on_file_new()
  7676. # Project options
  7677. self.options.update(d['options'])
  7678. self.project_filename = filename
  7679. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7680. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7681. if cli is None:
  7682. self.set_screen_units(self.options["units"])
  7683. # Re create objects
  7684. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7685. for obj in d['objs']:
  7686. def obj_init(obj_inst, app_inst):
  7687. try:
  7688. obj_inst.from_dict(obj)
  7689. except Exception as e:
  7690. print('App.open_project() --> ' + str(e))
  7691. return 'fail'
  7692. App.log.debug("Recreating from opened project an %s object: %s" %
  7693. (obj['kind'].capitalize(), obj['options']['name']))
  7694. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7695. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7696. if cli is None:
  7697. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7698. obj['kind'].upper(),
  7699. obj['options']['name']
  7700. )
  7701. )
  7702. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7703. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7704. self.should_we_save = False
  7705. self.file_opened.emit("project", filename)
  7706. # restore autosaving after a project was loaded
  7707. self.block_autosave = False
  7708. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7709. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7710. if cli is None:
  7711. self.set_ui_title(name=self.project_filename)
  7712. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7713. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7714. """
  7715. Re-generates all plots from all objects.
  7716. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7717. :param muted: if True don't print messages
  7718. :param use_thread: if True will use threading for plotting the objects
  7719. :return: None
  7720. """
  7721. self.log.debug("Plot_all()")
  7722. if muted is not True:
  7723. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7724. for plot_obj in self.collection.get_list():
  7725. def worker_task(obj):
  7726. with self.proc_container.new("Plotting"):
  7727. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7728. if fit_view is True:
  7729. self.app_obj.object_plotted.emit(obj)
  7730. if use_thread is True:
  7731. # Send to worker
  7732. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7733. else:
  7734. worker_task(plot_obj)
  7735. def register_folder(self, filename):
  7736. """
  7737. Register the last folder used by the app to open something
  7738. :param filename: the last folder is extracted from the filename
  7739. :return: None
  7740. """
  7741. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7742. def register_save_folder(self, filename):
  7743. """
  7744. Register the last folder used by the app to save something
  7745. :param filename: the last folder is extracted from the filename
  7746. :return: None
  7747. """
  7748. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7749. # def set_progress_bar(self, percentage, text=""):
  7750. # """
  7751. # Set a progress bar to a value (percentage)
  7752. #
  7753. # :param percentage: Value set to the progressbar
  7754. # :param text: Not used
  7755. # :return: None
  7756. # """
  7757. # self.ui.progress_bar.setValue(int(percentage))
  7758. def setup_recent_items(self):
  7759. """
  7760. Setup a dictionary with the recent files accessed, organized by type
  7761. :return:
  7762. """
  7763. icons = {
  7764. "gerber": self.resource_location + "/flatcam_icon16.png",
  7765. "excellon": self.resource_location + "/drill16.png",
  7766. 'geometry': self.resource_location + "/geometry16.png",
  7767. "cncjob": self.resource_location + "/cnc16.png",
  7768. "script": self.resource_location + "/script_new24.png",
  7769. "document": self.resource_location + "/notes16_1.png",
  7770. "project": self.resource_location + "/project16.png",
  7771. "svg": self.resource_location + "/geometry16.png",
  7772. "dxf": self.resource_location + "/dxf16.png",
  7773. "pdf": self.resource_location + "/pdf32.png",
  7774. "image": self.resource_location + "/image16.png"
  7775. }
  7776. try:
  7777. image_opener = self.image_tool.import_image
  7778. except AttributeError:
  7779. image_opener = None
  7780. openers = {
  7781. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7782. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7783. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7784. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7785. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7786. "document": None,
  7787. 'project': self.open_project,
  7788. 'svg': self.import_svg,
  7789. 'dxf': self.import_dxf,
  7790. 'image': image_opener,
  7791. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7792. }
  7793. # Open recent file for files
  7794. try:
  7795. f = open(self.data_path + '/recent.json')
  7796. except IOError:
  7797. App.log.error("Failed to load recent item list.")
  7798. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7799. return
  7800. try:
  7801. self.recent = json.load(f)
  7802. except json.errors.JSONDecodeError:
  7803. App.log.error("Failed to parse recent item list.")
  7804. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7805. f.close()
  7806. return
  7807. f.close()
  7808. # Open recent file for projects
  7809. try:
  7810. fp = open(self.data_path + '/recent_projects.json')
  7811. except IOError:
  7812. App.log.error("Failed to load recent project item list.")
  7813. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7814. return
  7815. try:
  7816. self.recent_projects = json.load(fp)
  7817. except json.errors.JSONDecodeError:
  7818. App.log.error("Failed to parse recent project item list.")
  7819. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7820. fp.close()
  7821. return
  7822. fp.close()
  7823. # Closure needed to create callbacks in a loop.
  7824. # Otherwise late binding occurs.
  7825. def make_callback(func, fname):
  7826. def opener():
  7827. func(fname)
  7828. return opener
  7829. def reset_recent_files():
  7830. # Reset menu
  7831. self.ui.recent.clear()
  7832. self.recent = []
  7833. try:
  7834. ff = open(self.data_path + '/recent.json', 'w')
  7835. except IOError:
  7836. App.log.error("Failed to open recent items file for writing.")
  7837. return
  7838. json.dump(self.recent, ff)
  7839. def reset_recent_projects():
  7840. # Reset menu
  7841. self.ui.recent_projects.clear()
  7842. self.recent_projects = []
  7843. try:
  7844. frp = open(self.data_path + '/recent_projects.json', 'w')
  7845. except IOError:
  7846. App.log.error("Failed to open recent projects items file for writing.")
  7847. return
  7848. json.dump(self.recent, frp)
  7849. # Reset menu
  7850. self.ui.recent.clear()
  7851. self.ui.recent_projects.clear()
  7852. # Create menu items for projects
  7853. for recent in self.recent_projects:
  7854. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7855. if recent['kind'] == 'project':
  7856. try:
  7857. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7858. # Attach callback
  7859. o = make_callback(openers[recent["kind"]], recent['filename'])
  7860. action.triggered.connect(o)
  7861. self.ui.recent_projects.addAction(action)
  7862. except KeyError:
  7863. App.log.error("Unsupported file type: %s" % recent["kind"])
  7864. # Last action in Recent Files menu is one that Clear the content
  7865. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7866. (_("Clear Recent projects")), self)
  7867. clear_action_proj.triggered.connect(reset_recent_projects)
  7868. self.ui.recent_projects.addSeparator()
  7869. self.ui.recent_projects.addAction(clear_action_proj)
  7870. # Create menu items for files
  7871. for recent in self.recent:
  7872. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7873. if recent['kind'] != 'project':
  7874. try:
  7875. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7876. # Attach callback
  7877. o = make_callback(openers[recent["kind"]], recent['filename'])
  7878. action.triggered.connect(o)
  7879. self.ui.recent.addAction(action)
  7880. except KeyError:
  7881. App.log.error("Unsupported file type: %s" % recent["kind"])
  7882. # Last action in Recent Files menu is one that Clear the content
  7883. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7884. (_("Clear Recent files")), self)
  7885. clear_action.triggered.connect(reset_recent_files)
  7886. self.ui.recent.addSeparator()
  7887. self.ui.recent.addAction(clear_action)
  7888. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7889. # self.ui.menufilerecent.set_submenu(recent_menu)
  7890. # recent_menu.show_all()
  7891. # self.ui.recent.show()
  7892. self.log.debug("Recent items list has been populated.")
  7893. def setup_component_editor(self):
  7894. """
  7895. Default text for the Selected tab when is not taken by the Object UI.
  7896. :return:
  7897. """
  7898. # label = QtWidgets.QLabel("Choose an item from Project")
  7899. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7900. sel_title = QtWidgets.QTextEdit(
  7901. _('<b>Shortcut Key List</b>'))
  7902. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7903. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7904. f_settings = QSettings("Open Source", "FlatCAM")
  7905. if f_settings.contains("notebook_font_size"):
  7906. fsize = f_settings.value('notebook_font_size', type=int)
  7907. else:
  7908. fsize = 12
  7909. tsize = fsize + int(fsize / 2)
  7910. # selected_text = (_('''
  7911. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7912. # </p>
  7913. #
  7914. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7915. # The normal flow when working in FlatCAM is the following:</span></p>
  7916. #
  7917. # <ol>
  7918. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7919. # file into
  7920. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7921. # even dragging and dropping the files on the appGUI.<br />
  7922. # <br />
  7923. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7924. # drop of the
  7925. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7926. # &nbsp;</li>
  7927. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7928. # and then
  7929. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7930. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7931. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7932. # <br />
  7933. # If the selection of the object is done on the canvas by single click instead, and the
  7934. # <strong>SELECTED TAB</strong>
  7935. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7936. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7937. # it even if it was out of focus.<br />
  7938. # <br />
  7939. # You can change the parameters in this screen and the flow direction is like this:<br />
  7940. # <br />
  7941. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7942. # <strong> Geometry Object
  7943. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7944. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7945. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7946. # </ol>
  7947. #
  7948. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7949. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7950. # <strong>F3</strong>.</span></p>
  7951. #
  7952. # ''').format(fsize=fsize, tsize=tsize))
  7953. selected_text = '''
  7954. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7955. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7956. {s1}</span></p>
  7957. <ol>
  7958. <li><span style="font-size:{fsize}px">{s2}<br />
  7959. <br />
  7960. {s3}</span><br />
  7961. &nbsp;</li>
  7962. <li><span style="font-size:{fsize}px">{s4}<br />
  7963. &nbsp;</li>
  7964. <br />
  7965. <li><span style="font-size:{fsize}px">{s5}<br />
  7966. &nbsp;</li>
  7967. <br />
  7968. <li><span style="font-size:{fsize}px">{s6}<br />
  7969. <br />
  7970. {s7}</span></li>
  7971. </ol>
  7972. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7973. '''.format(
  7974. title=_("Selected Tab - Choose an Item from Project Tab"),
  7975. subtitle=_("Details"),
  7976. s1=_("The normal flow when working with the application is the following:"),
  7977. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7978. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7979. "files on the GUI."),
  7980. s3=_("You can also load a project by double clicking on the project file, "
  7981. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7982. "actions offered within the app."),
  7983. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7984. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7985. "SELECTED TAB will be updated with the object properties according to its kind: "
  7986. "Gerber, Excellon, Geometry or CNCJob object."),
  7987. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7988. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7989. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7990. "the SELECTED TAB and populate it even if it was out of focus."),
  7991. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7992. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7993. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7994. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7995. "(again, done in SELECTED TAB) --> Save GCode."),
  7996. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7997. "or through its own key shortcut: <b>F3</b>."),
  7998. tsize=tsize,
  7999. fsize=fsize
  8000. )
  8001. sel_title.setText(selected_text)
  8002. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8003. self.ui.selected_scroll_area.setWidget(sel_title)
  8004. def setup_obj_classes(self):
  8005. """
  8006. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8007. class.
  8008. :return: None
  8009. """
  8010. FlatCAMObj.app = self
  8011. ObjectCollection.app = self
  8012. Gerber.app = self
  8013. Excellon.app = self
  8014. Geometry.app = self
  8015. CNCjob.app = self
  8016. FCProcess.app = self
  8017. FCProcessContainer.app = self
  8018. OptionsGroupUI.app = self
  8019. def version_check(self):
  8020. """
  8021. Checks for the latest version of the program. Alerts the
  8022. user if theirs is outdated. This method is meant to be run
  8023. in a separate thread.
  8024. :return: None
  8025. """
  8026. self.log.debug("version_check()")
  8027. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8028. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8029. App.version_url,
  8030. str(self.defaults['global_serial']),
  8031. str(self.version),
  8032. str(self.os),
  8033. urllib.parse.urlencode(self.defaults["global_stats"])
  8034. )
  8035. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8036. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8037. # urllib.parse.urlencode(self.defaults["global_stats"])
  8038. else:
  8039. # no_stats dict; just so it won't break things on website
  8040. no_ststs_dict = {}
  8041. no_ststs_dict["global_ststs"] = {}
  8042. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  8043. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8044. App.log.debug("Checking for updates @ %s" % full_url)
  8045. # ## Get the data
  8046. try:
  8047. f = urllib.request.urlopen(full_url)
  8048. except Exception:
  8049. # App.log.warning("Failed checking for latest version. Could not connect.")
  8050. self.log.warning("Failed checking for latest version. Could not connect.")
  8051. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8052. return
  8053. try:
  8054. data = json.load(f)
  8055. except Exception as e:
  8056. App.log.error("Could not parse information about latest version.")
  8057. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8058. App.log.debug("json.load(): %s" % str(e))
  8059. f.close()
  8060. return
  8061. f.close()
  8062. # ## Latest version?
  8063. if self.version >= data["version"]:
  8064. App.log.debug("FlatCAM is up to date!")
  8065. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8066. return
  8067. App.log.debug("Newer version available.")
  8068. self.message.emit(
  8069. _("Newer Version Available"),
  8070. '%s<br><br>><b>%s</b><br>%s' % (
  8071. _("There is a newer version of FlatCAM available for download:"),
  8072. str(data["name"]),
  8073. str(data["message"])
  8074. ),
  8075. _("info")
  8076. )
  8077. def on_plotcanvas_setup(self, container=None):
  8078. """
  8079. This is doing the setup for the plot area (canvas).
  8080. :param container: QT Widget where to install the canvas
  8081. :return: None
  8082. """
  8083. if container:
  8084. plot_container = container
  8085. else:
  8086. plot_container = self.ui.right_layout
  8087. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8088. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8089. self.is_legacy = True
  8090. self.defaults["global_graphic_engine"] = "2D"
  8091. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8092. else:
  8093. try:
  8094. self.plotcanvas = PlotCanvas(plot_container, self)
  8095. except Exception as er:
  8096. msg_txt = traceback.format_exc()
  8097. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8098. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8099. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8100. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8101. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8102. msg += msg_txt
  8103. self.inform.emit(msg)
  8104. return 'fail'
  8105. # So it can receive key presses
  8106. self.plotcanvas.native.setFocus()
  8107. if self.is_legacy is False:
  8108. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8109. # Set the mouse button for panning
  8110. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8111. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8112. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8113. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8114. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8115. # Keys over plot enabled
  8116. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8117. if self.defaults['global_cursor_type'] == 'small':
  8118. self.app_cursor = self.plotcanvas.new_cursor()
  8119. else:
  8120. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8121. if self.ui.grid_snap_btn.isChecked():
  8122. self.app_cursor.enabled = True
  8123. else:
  8124. self.app_cursor.enabled = False
  8125. if self.is_legacy is False:
  8126. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8127. else:
  8128. # will use the default Matplotlib axes
  8129. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8130. def on_zoom_fit(self):
  8131. """
  8132. Callback for zoom-fit request. This can be either from the corresponding
  8133. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8134. with axes limits from the geometry bounds of all objects.
  8135. :return: None
  8136. """
  8137. if self.is_legacy is False:
  8138. self.plotcanvas.fit_view()
  8139. else:
  8140. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8141. width = xmax - xmin
  8142. height = ymax - ymin
  8143. xmin -= 0.05 * width
  8144. xmax += 0.05 * width
  8145. ymin -= 0.05 * height
  8146. ymax += 0.05 * height
  8147. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8148. def on_zoom_in(self):
  8149. """
  8150. Callback for zoom-in request.
  8151. :return:
  8152. """
  8153. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8154. def on_zoom_out(self):
  8155. """
  8156. Callback for zoom-out request.
  8157. :return:
  8158. """
  8159. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8160. def disable_all_plots(self):
  8161. self.defaults.report_usage("disable_all_plots()")
  8162. self.disable_plots(self.collection.get_list())
  8163. self.inform.emit('[success] %s' %
  8164. _("All plots disabled."))
  8165. def disable_other_plots(self):
  8166. self.defaults.report_usage("disable_other_plots()")
  8167. self.disable_plots(self.collection.get_non_selected())
  8168. self.inform.emit('[success] %s' %
  8169. _("All non selected plots disabled."))
  8170. def enable_all_plots(self):
  8171. self.defaults.report_usage("enable_all_plots()")
  8172. self.enable_plots(self.collection.get_list())
  8173. self.inform.emit('[success] %s' %
  8174. _("All plots enabled."))
  8175. def on_enable_sel_plots(self):
  8176. log.debug("App.on_enable_sel_plot()")
  8177. object_list = self.collection.get_selected()
  8178. self.enable_plots(objects=object_list)
  8179. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8180. def on_disable_sel_plots(self):
  8181. log.debug("App.on_disable_sel_plot()")
  8182. # self.inform.emit(_("Disabling plots ..."))
  8183. object_list = self.collection.get_selected()
  8184. self.disable_plots(objects=object_list)
  8185. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8186. def enable_plots(self, objects):
  8187. """
  8188. Enable plots
  8189. :param objects: list of Objects to be enabled
  8190. :return:
  8191. """
  8192. log.debug("Enabling plots ...")
  8193. # self.inform.emit(_("Working ..."))
  8194. for obj in objects:
  8195. if obj.options['plot'] is False:
  8196. obj.options.set_change_callback(lambda x: None)
  8197. obj.options['plot'] = True
  8198. try:
  8199. # only the Gerber obj has on_plot_cb_click() method
  8200. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8201. # disable this cb while disconnected,
  8202. # in case the operation takes time the user is not allowed to change it
  8203. obj.ui.plot_cb.setDisabled(True)
  8204. except AttributeError:
  8205. pass
  8206. obj.set_form_item("plot")
  8207. try:
  8208. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8209. obj.ui.plot_cb.setDisabled(False)
  8210. except AttributeError:
  8211. pass
  8212. obj.options.set_change_callback(obj.on_options_change)
  8213. def worker_task(objs):
  8214. with self.proc_container.new(_("Enabling plots ...")):
  8215. for plot_obj in objs:
  8216. # obj.options['plot'] = True
  8217. if isinstance(plot_obj, CNCJobObject):
  8218. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8219. else:
  8220. plot_obj.plot(visible=True)
  8221. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8222. def disable_plots(self, objects):
  8223. """
  8224. Disables plots
  8225. :param objects: list of Objects to be disabled
  8226. :return:
  8227. """
  8228. # if no objects selected then do nothing
  8229. if not self.collection.get_selected():
  8230. return
  8231. log.debug("Disabling plots ...")
  8232. # self.inform.emit(_("Working ..."))
  8233. for obj in objects:
  8234. if obj.options['plot'] is True:
  8235. obj.options.set_change_callback(lambda x: None)
  8236. obj.options['plot'] = False
  8237. try:
  8238. # only the Gerber obj has on_plot_cb_click() method
  8239. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8240. obj.ui.plot_cb.setDisabled(True)
  8241. except AttributeError:
  8242. pass
  8243. obj.set_form_item("plot")
  8244. try:
  8245. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8246. obj.ui.plot_cb.setDisabled(False)
  8247. except AttributeError:
  8248. pass
  8249. obj.options.set_change_callback(obj.on_options_change)
  8250. try:
  8251. self.delete_selection_shape()
  8252. except Exception as e:
  8253. log.debug("App.disable_plots() --> %s" % str(e))
  8254. def worker_task(objs):
  8255. with self.proc_container.new(_("Disabling plots ...")):
  8256. for plot_obj in objs:
  8257. # obj.options['plot'] = True
  8258. if isinstance(plot_obj, CNCJobObject):
  8259. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8260. else:
  8261. plot_obj.plot(visible=False)
  8262. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8263. def toggle_plots(self, objects):
  8264. """
  8265. Toggle plots visibility
  8266. :param objects: list of Objects for which to be toggled the visibility
  8267. :return: None
  8268. """
  8269. # if no objects selected then do nothing
  8270. if not self.collection.get_selected():
  8271. return
  8272. log.debug("Toggling plots ...")
  8273. self.inform.emit(_("Working ..."))
  8274. for obj in objects:
  8275. if obj.options['plot'] is False:
  8276. obj.options['plot'] = True
  8277. else:
  8278. obj.options['plot'] = False
  8279. self.app_obj.plots_updated.emit()
  8280. def clear_plots(self):
  8281. """
  8282. Clear the plots
  8283. :return: None
  8284. """
  8285. objects = self.collection.get_list()
  8286. for obj in objects:
  8287. obj.clear(obj == objects[-1])
  8288. # Clear pool to free memory
  8289. self.clear_pool()
  8290. def on_set_color_action_triggered(self):
  8291. """
  8292. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8293. :return:
  8294. """
  8295. new_color = self.defaults['gerber_plot_fill']
  8296. clicked_action = self.sender()
  8297. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8298. act_name = clicked_action.text()
  8299. sel_obj_list = self.collection.get_selected()
  8300. if not sel_obj_list:
  8301. return
  8302. # a default value, I just chose this one
  8303. alpha_level = 'BF'
  8304. for sel_obj in sel_obj_list:
  8305. if sel_obj.kind == 'excellon':
  8306. alpha_level = str(hex(
  8307. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8308. elif sel_obj.kind == 'gerber':
  8309. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8310. elif sel_obj.kind == 'geometry':
  8311. alpha_level = 'FF'
  8312. else:
  8313. log.debug(
  8314. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8315. continue
  8316. sel_obj.alpha_level = alpha_level
  8317. if act_name == _('Red'):
  8318. new_color = '#FF0000' + alpha_level
  8319. if act_name == _('Blue'):
  8320. new_color = '#0000FF' + alpha_level
  8321. if act_name == _('Yellow'):
  8322. new_color = '#FFDF00' + alpha_level
  8323. if act_name == _('Green'):
  8324. new_color = '#00FF00' + alpha_level
  8325. if act_name == _('Purple'):
  8326. new_color = '#FF00FF' + alpha_level
  8327. if act_name == _('Brown'):
  8328. new_color = '#A52A2A' + alpha_level
  8329. if act_name == _('White'):
  8330. new_color = '#FFFFFF' + alpha_level
  8331. if act_name == _('Black'):
  8332. new_color = '#000000' + alpha_level
  8333. if act_name == _('Custom'):
  8334. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8335. c_dialog = QtWidgets.QColorDialog()
  8336. plot_fill_color = c_dialog.getColor(initial=new_color)
  8337. if plot_fill_color.isValid() is False:
  8338. return
  8339. new_color = str(plot_fill_color.name()) + alpha_level
  8340. if act_name == _("Default"):
  8341. for sel_obj in sel_obj_list:
  8342. if sel_obj.kind == 'excellon':
  8343. new_color = self.defaults['excellon_plot_fill']
  8344. new_line_color = self.defaults['excellon_plot_line']
  8345. elif sel_obj.kind == 'gerber':
  8346. new_color = self.defaults['gerber_plot_fill']
  8347. new_line_color = self.defaults['gerber_plot_line']
  8348. elif sel_obj.kind == 'geometry':
  8349. new_color = self.defaults['geometry_plot_line']
  8350. new_line_color = self.defaults['geometry_plot_line']
  8351. else:
  8352. log.debug(
  8353. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8354. continue
  8355. sel_obj.fill_color = new_color
  8356. sel_obj.outline_color = new_line_color
  8357. sel_obj.shapes.redraw(
  8358. update_colors=(new_color, new_line_color)
  8359. )
  8360. return
  8361. if act_name == _("Opacity"):
  8362. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8363. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8364. if ok_button:
  8365. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8366. for sel_obj in sel_obj_list:
  8367. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8368. sel_obj.shapes.redraw(
  8369. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8370. )
  8371. return
  8372. new_line_color = color_variant(new_color[:7], 0.7)
  8373. if act_name == _("White"):
  8374. new_line_color = color_variant("#dedede", 0.7)
  8375. for sel_obj in sel_obj_list:
  8376. sel_obj.fill_color = new_color
  8377. sel_obj.outline_color = new_line_color
  8378. sel_obj.shapes.redraw(
  8379. update_colors=(new_color, new_line_color)
  8380. )
  8381. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8382. group = self.collection.group_items["gerber"]
  8383. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8384. new_c = (new_line_color, new_color)
  8385. for sel_obj in sel_obj_list:
  8386. if sel_obj.kind == 'gerber':
  8387. item = sel_obj.item
  8388. item_index = self.collection.index(item.row(), 0, group_index)
  8389. idx = item_index.row()
  8390. self.defaults["gerber_color_list"][idx] = new_c
  8391. def generate_cnc_job(self, objects):
  8392. """
  8393. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8394. :param objects: Selected objects in the Project Tab
  8395. :return:
  8396. """
  8397. self.defaults.report_usage("generate_cnc_job()")
  8398. # for obj in objects:
  8399. # obj.generatecncjob()
  8400. for obj in objects:
  8401. obj.on_generatecnc_button_click()
  8402. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8403. """
  8404. Saves the current project to the specified file.
  8405. :param filename: Name of the file in which to save.
  8406. :type filename: str
  8407. :param quit_action: if the project saving will be followed by an app quit; boolean
  8408. :param silent: if True will not display status messages
  8409. :param from_tcl True is run from Tcl Shell
  8410. :return: None
  8411. """
  8412. self.log.debug("save_project()")
  8413. self.save_in_progress = True
  8414. with self.proc_container.new(_("Saving FlatCAM Project")):
  8415. # Capture the latest changes
  8416. # Current object
  8417. try:
  8418. current_object = self.collection.get_active()
  8419. if current_object:
  8420. current_object.read_form()
  8421. except Exception as e:
  8422. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8423. pass
  8424. # Serialize the whole project
  8425. d = {
  8426. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8427. "options": self.options,
  8428. "version": self.version
  8429. }
  8430. if self.defaults["global_save_compressed"] is True:
  8431. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8432. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8433. # # Write
  8434. f.write(g)
  8435. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8436. else:
  8437. # Open file
  8438. try:
  8439. f = open(filename, 'w')
  8440. except IOError:
  8441. App.log.error("Failed to open file for saving: %s", filename)
  8442. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8443. return
  8444. # Write
  8445. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8446. f.close()
  8447. # verification of the saved project
  8448. # Open and parse
  8449. try:
  8450. saved_f = open(filename, 'r')
  8451. except IOError:
  8452. if silent is False:
  8453. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8454. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8455. return
  8456. try:
  8457. saved_d = json.load(saved_f, object_hook=dict2obj)
  8458. except Exception:
  8459. if silent is False:
  8460. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8461. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8462. f.close()
  8463. return
  8464. saved_f.close()
  8465. if silent is False:
  8466. if 'version' in saved_d:
  8467. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8468. else:
  8469. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8470. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8471. tb_settings = QSettings("Open Source", "FlatCAM")
  8472. lock_state = self.ui.lock_action.isChecked()
  8473. tb_settings.setValue('toolbar_lock', lock_state)
  8474. # This will write the setting to the platform specific storage.
  8475. del tb_settings
  8476. # if quit:
  8477. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8478. # t.start()
  8479. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8480. def start_delayed_quit(self, delay, filename, should_quit=None):
  8481. """
  8482. :param delay: period of checking if project file size is more than zero; in seconds
  8483. :param filename: the name of the project file to be checked periodically for size more than zero
  8484. :param should_quit: if the task finished will be followed by an app quit; boolean
  8485. :return:
  8486. """
  8487. to_quit = should_quit
  8488. self.save_timer = QtCore.QTimer()
  8489. self.save_timer.setInterval(delay)
  8490. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8491. self.save_timer.start()
  8492. def check_project_file_size(self, filename, should_quit=None):
  8493. """
  8494. :param filename: the name of the project file to be checked periodically for size more than zero
  8495. :param should_quit: will quit the app if True; boolean
  8496. :return:
  8497. """
  8498. try:
  8499. if os.stat(filename).st_size > 0:
  8500. self.save_in_progress = False
  8501. self.save_timer.stop()
  8502. if should_quit:
  8503. self.app_quit.emit()
  8504. except Exception:
  8505. traceback.print_exc()
  8506. def save_project_auto(self):
  8507. """
  8508. Called periodically to save the project.
  8509. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8510. # progress.
  8511. :return:
  8512. """
  8513. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8514. self.on_file_saveproject()
  8515. def save_project_auto_update(self):
  8516. """
  8517. Update the auto save time interval value.
  8518. :return:
  8519. """
  8520. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8521. try:
  8522. if self.autosave_timer.isActive():
  8523. self.autosave_timer.stop()
  8524. except Exception:
  8525. pass
  8526. if self.defaults['global_autosave'] is True:
  8527. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8528. self.autosave_timer.start()
  8529. def on_options_app2project(self):
  8530. """
  8531. Callback for Options->Transfer Options->App=>Project. Copies options
  8532. from application defaults to project defaults.
  8533. :return: None
  8534. """
  8535. self.defaults.report_usage("on_options_app2project")
  8536. self.preferencesUiManager.defaults_read_form()
  8537. self.options.update(self.defaults)
  8538. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8539. """
  8540. Shows a message on the FlatCAM Shell
  8541. :param msg: Message to display.
  8542. :param show: Opens the shell.
  8543. :param error: Shows the message as an error.
  8544. :param warning: Shows the message as an warning.
  8545. :param success: Shows the message as an success.
  8546. :param selected: Indicate that something was selected on canvas
  8547. :return: None
  8548. """
  8549. if show:
  8550. self.ui.shell_dock.show()
  8551. try:
  8552. if error:
  8553. self.shell.append_error(msg + "\n")
  8554. elif warning:
  8555. self.shell.append_warning(msg + "\n")
  8556. elif success:
  8557. self.shell.append_success(msg + "\n")
  8558. elif selected:
  8559. self.shell.append_selected(msg + "\n")
  8560. else:
  8561. self.shell.append_output(msg + "\n")
  8562. except AttributeError:
  8563. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8564. def dec_format(self, val, dec=None):
  8565. """
  8566. Returns a formatted float value with a certain number of decimals
  8567. """
  8568. dec_nr = dec if dec is not None else self.decimals
  8569. return float('%.*f' % (dec_nr, val))
  8570. class ArgsThread(QtCore.QObject):
  8571. open_signal = pyqtSignal(list)
  8572. start = pyqtSignal()
  8573. stop = pyqtSignal()
  8574. if sys.platform == 'win32':
  8575. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8576. else:
  8577. address = ('/tmp/testipc', 'AF_UNIX')
  8578. def __init__(self):
  8579. super().__init__()
  8580. self.listener = None
  8581. self.thread_exit = False
  8582. self.start.connect(self.run)
  8583. self.stop.connect(self.close_listener)
  8584. def my_loop(self, address):
  8585. try:
  8586. self.listener = Listener(*address)
  8587. while self.thread_exit is False:
  8588. conn = self.listener.accept()
  8589. self.serve(conn)
  8590. except socket.error:
  8591. try:
  8592. conn = Client(*address)
  8593. conn.send(sys.argv)
  8594. conn.send('close')
  8595. # close the current instance only if there are args
  8596. if len(sys.argv) > 1:
  8597. try:
  8598. self.listener.close()
  8599. except Exception:
  8600. pass
  8601. sys.exit()
  8602. except ConnectionRefusedError:
  8603. if sys.platform == 'win32':
  8604. pass
  8605. else:
  8606. os.system('rm /tmp/testipc')
  8607. self.listener = Listener(*address)
  8608. while True:
  8609. conn = self.listener.accept()
  8610. self.serve(conn)
  8611. def serve(self, conn):
  8612. while self.thread_exit is False:
  8613. msg = conn.recv()
  8614. if msg == 'close':
  8615. break
  8616. self.open_signal.emit(msg)
  8617. conn.close()
  8618. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8619. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8620. @pyqtSlot()
  8621. def run(self):
  8622. self.my_loop(self.address)
  8623. @pyqtSlot()
  8624. def close_listener(self):
  8625. self.thread_exit = True
  8626. self.listener.close()
  8627. # end of file